diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 121ace97..94046873 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,4 +52,3 @@ jobs: - name: Run tests run: ./scripts/test - diff --git a/.gitignore b/.gitignore index 39c31e3e..4e81838d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ .prism.log .gradle .idea +.kotlin build codegen.log kls_database.db diff --git a/.release-please-manifest.json b/.release-please-manifest.json index bd7f3844..8e76abb5 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "4.2.0" + ".": "5.0.0" } \ No newline at end of file diff --git a/.stats.yml b/.stats.yml index bed01067..e3e52833 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,4 @@ -configured_endpoints: 40 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/finch%2Ffinch-7a816d4a5f0039230590a6662f3513d5756344ca662761ecbc49016593f65836.yml +configured_endpoints: 45 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/finch%2Ffinch-14d375aab89e6b212fe459805a42d6ea7d7da8eae2037ae710a187d06911be1d.yml +openapi_spec_hash: 08b86ecbec3323717d48e4aaee48ed54 +config_hash: ce10384813f68ba3fed61c7b601b396b diff --git a/CHANGELOG.md b/CHANGELOG.md index a4a094f3..be5fb27e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,107 @@ # Changelog +## 5.0.0 (2025-04-08) + +Full Changelog: [v4.2.0...v5.0.0](https://github.com/Finch-API/finch-api-java/compare/v4.2.0...v5.0.0) + +### ⚠ BREAKING CHANGES + +* **client:** refactor exception structure and methods ([#505](https://github.com/Finch-API/finch-api-java/issues/505)) +* **client:** refactor multipart formdata impl ([#473](https://github.com/Finch-API/finch-api-java/issues/473)) + +### Features + +* **api:** add new endpoints for pay statement items ([#526](https://github.com/Finch-API/finch-api-java/issues/526)) ([1ab19a3](https://github.com/Finch-API/finch-api-java/commit/1ab19a34148407ce143df4d49697af386e17f560)) +* **api:** api update ([#513](https://github.com/Finch-API/finch-api-java/issues/513)) ([5849824](https://github.com/Finch-API/finch-api-java/commit/5849824f4a7704255935cd6e13c1761427b8ca62)) +* **api:** api update ([#515](https://github.com/Finch-API/finch-api-java/issues/515)) ([dffd823](https://github.com/Finch-API/finch-api-java/commit/dffd823f5649b18ca44e06d5f0f8bcb68ba43879)) +* **api:** api update ([#517](https://github.com/Finch-API/finch-api-java/issues/517)) ([0123042](https://github.com/Finch-API/finch-api-java/commit/01230422dedfd1f4432fc84e4ed517eaf31319a9)) +* **api:** api update ([#520](https://github.com/Finch-API/finch-api-java/issues/520)) ([a6b3092](https://github.com/Finch-API/finch-api-java/commit/a6b3092d8ce9e17f78f267d36467ca2057e6ac1f)) +* **api:** api update ([#523](https://github.com/Finch-API/finch-api-java/issues/523)) ([842bb3f](https://github.com/Finch-API/finch-api-java/commit/842bb3fa15300004eea197bb5a8f57365f1eee78)) +* **api:** manual updates ([#477](https://github.com/Finch-API/finch-api-java/issues/477)) ([83f00bd](https://github.com/Finch-API/finch-api-java/commit/83f00bd2aadd9049da1d8365dfa9bdd03d52a159)) +* **api:** manual updates ([#527](https://github.com/Finch-API/finch-api-java/issues/527)) ([b5a2343](https://github.com/Finch-API/finch-api-java/commit/b5a2343b89278949689abdfb5b1303713ac57fbf)) +* **client:** accept `InputStream` and `Path` for file params ([#479](https://github.com/Finch-API/finch-api-java/issues/479)) ([721cd2c](https://github.com/Finch-API/finch-api-java/commit/721cd2c2696a8929f3b7bbe27ba5df82f872df4f)) +* **client:** add enum validation method ([1bd0c25](https://github.com/Finch-API/finch-api-java/commit/1bd0c2538ce50578fcd7ae51c944cdfb0736aa9b)) +* **client:** allow configuring timeouts granularly ([#470](https://github.com/Finch-API/finch-api-java/issues/470)) ([4d3b414](https://github.com/Finch-API/finch-api-java/commit/4d3b414c120045834dc829e12cbc185c88fe2764)) +* **client:** detect binary incompatible jackson versions ([#480](https://github.com/Finch-API/finch-api-java/issues/480)) ([fcf521a](https://github.com/Finch-API/finch-api-java/commit/fcf521a7e262ad96d7f3703114b221a4d2622d50)) +* **client:** expose request body setter and getter ([#524](https://github.com/Finch-API/finch-api-java/issues/524)) ([1b97fe6](https://github.com/Finch-API/finch-api-java/commit/1b97fe6e3dc9b0e83c9f267fd37e985258b958e5)) +* **client:** make datetime deserialization more lenient ([#522](https://github.com/Finch-API/finch-api-java/issues/522)) ([c7265b7](https://github.com/Finch-API/finch-api-java/commit/c7265b7fec4baacc24dba2415a9bb734731a46e3)) +* **client:** make union deserialization more robust ([#521](https://github.com/Finch-API/finch-api-java/issues/521)) ([1bd0c25](https://github.com/Finch-API/finch-api-java/commit/1bd0c2538ce50578fcd7ae51c944cdfb0736aa9b)) +* **client:** support a lower jackson version ([#512](https://github.com/Finch-API/finch-api-java/issues/512)) ([2897011](https://github.com/Finch-API/finch-api-java/commit/289701192191a42ca4f28eabb6ac73651f7d9909)) +* **client:** support raw response access ([#471](https://github.com/Finch-API/finch-api-java/issues/471)) ([481c99c](https://github.com/Finch-API/finch-api-java/commit/481c99cf2bc062b137c99a69bfce289c3e570a5a)) +* **client:** throw on incompatible jackson version ([2897011](https://github.com/Finch-API/finch-api-java/commit/289701192191a42ca4f28eabb6ac73651f7d9909)) +* generate and publish docs ([#481](https://github.com/Finch-API/finch-api-java/issues/481)) ([c5c4196](https://github.com/Finch-API/finch-api-java/commit/c5c4196d609a6db22887e580ad14323506f0aa2a)) + + +### Bug Fixes + +* **client:** don't call `validate()` during deserialization if we don't have to ([#516](https://github.com/Finch-API/finch-api-java/issues/516)) ([e988e9d](https://github.com/Finch-API/finch-api-java/commit/e988e9da5f57c5d201021842312fd60ae4c41ae1)) +* **client:** limit json deserialization coercion ([#518](https://github.com/Finch-API/finch-api-java/issues/518)) ([0bd7dd5](https://github.com/Finch-API/finch-api-java/commit/0bd7dd5974c4d30f0adc02b6af1f4f227d2c743e)) +* **client:** map deserialization bug ([8d03e6d](https://github.com/Finch-API/finch-api-java/commit/8d03e6dd61fa910bcd9788a58ad4cbd0141356ac)) +* **client:** return `Optional<T>` instead of `Optional` ([#529](https://github.com/Finch-API/finch-api-java/issues/529)) ([8b601dc](https://github.com/Finch-API/finch-api-java/commit/8b601dc398296e351a1f0590ef858063fec9f48a)) +* **client:** support kotlin 1.8 runtime ([#502](https://github.com/Finch-API/finch-api-java/issues/502)) ([0fb2cbc](https://github.com/Finch-API/finch-api-java/commit/0fb2cbc5711394b6f823e5e9c985cd64b11bbc21)) +* compilation error ([ebc6f30](https://github.com/Finch-API/finch-api-java/commit/ebc6f30543123460b1c6f297c6c1ad32453ff77c)) +* pluralize `list` response variables ([#519](https://github.com/Finch-API/finch-api-java/issues/519)) ([17c4e8f](https://github.com/Finch-API/finch-api-java/commit/17c4e8fbbf4698f67ddcfedb383d677e5e5a9d1d)) +* **tests:** fix jackson attributes ([3ccd785](https://github.com/Finch-API/finch-api-java/commit/3ccd785da8291d41d74aa71bfaa604b5a38295b6)) + + +### Performance Improvements + +* **client:** cached parsed type in `HttpResponseFor` ([#525](https://github.com/Finch-API/finch-api-java/issues/525)) ([16616bf](https://github.com/Finch-API/finch-api-java/commit/16616bf6a5dab5996375d41d9b8404fb2928ac89)) + + +### Chores + +* **client:** expose `Optional`, not nullable, from `ClientOptions` ([#476](https://github.com/Finch-API/finch-api-java/issues/476)) ([fc827bc](https://github.com/Finch-API/finch-api-java/commit/fc827bc6bd38e80bf7f09b241e559e46d7adcf2a)) +* **client:** refactor exception structure and methods ([#505](https://github.com/Finch-API/finch-api-java/issues/505)) ([4be4f06](https://github.com/Finch-API/finch-api-java/commit/4be4f068408cf19a55f8fcc1b64aac6fc24fd73d)) +* **client:** refactor multipart formdata impl ([#473](https://github.com/Finch-API/finch-api-java/issues/473)) ([7cb2a7f](https://github.com/Finch-API/finch-api-java/commit/7cb2a7f642d7bcaf67deec5d5f355682fe9b8e3e)) +* **client:** remove unnecessary json state from some query param classes ([1bd0c25](https://github.com/Finch-API/finch-api-java/commit/1bd0c2538ce50578fcd7ae51c944cdfb0736aa9b)) +* **internal:** add `.kotlin` to `.gitignore` ([#483](https://github.com/Finch-API/finch-api-java/issues/483)) ([473058a](https://github.com/Finch-API/finch-api-java/commit/473058a82d86a318c3c467d60e6cedfcd416fb22)) +* **internal:** add generated comment ([#496](https://github.com/Finch-API/finch-api-java/issues/496)) ([9543169](https://github.com/Finch-API/finch-api-java/commit/9543169b8b1af2c39666c6be1df6ea40f0e1a67f)) +* **internal:** add invalid json deserialization tests ([1bd0c25](https://github.com/Finch-API/finch-api-java/commit/1bd0c2538ce50578fcd7ae51c944cdfb0736aa9b)) +* **internal:** add json roundtripping tests ([1bd0c25](https://github.com/Finch-API/finch-api-java/commit/1bd0c2538ce50578fcd7ae51c944cdfb0736aa9b)) +* **internal:** add some tests for union classes ([#501](https://github.com/Finch-API/finch-api-java/issues/501)) ([4aff498](https://github.com/Finch-API/finch-api-java/commit/4aff4981754d9336e20b29713c5b95a03819dfec)) +* **internal:** codegen related update ([60e5c13](https://github.com/Finch-API/finch-api-java/commit/60e5c131ff4b41265efd39bff4c29a6c1a4df442)) +* **internal:** codegen related update ([#469](https://github.com/Finch-API/finch-api-java/issues/469)) ([a308954](https://github.com/Finch-API/finch-api-java/commit/a3089549cd0743446d2b906db5fcd830f579ddd8)) +* **internal:** codegen related update ([#488](https://github.com/Finch-API/finch-api-java/issues/488)) ([5742de2](https://github.com/Finch-API/finch-api-java/commit/5742de269c36314324b0fb8f4214efb87af09dff)) +* **internal:** codegen related update ([#504](https://github.com/Finch-API/finch-api-java/issues/504)) ([9be38e0](https://github.com/Finch-API/finch-api-java/commit/9be38e0fce500731d023902658ec0fa8926b27e1)) +* **internal:** codegen related update ([#531](https://github.com/Finch-API/finch-api-java/issues/531)) ([433f15a](https://github.com/Finch-API/finch-api-java/commit/433f15ad426ef4e24d4ca9c0bf7254d2b6a859bc)) +* **internal:** delete duplicate tests ([d1b1bd2](https://github.com/Finch-API/finch-api-java/commit/d1b1bd2847f0ffa069f9d9bce5702f093b129797)) +* **internal:** delete unused methods and annotations ([#514](https://github.com/Finch-API/finch-api-java/issues/514)) ([8d03e6d](https://github.com/Finch-API/finch-api-java/commit/8d03e6dd61fa910bcd9788a58ad4cbd0141356ac)) +* **internal:** don't use `JvmOverloads` in interfaces ([0d38744](https://github.com/Finch-API/finch-api-java/commit/0d387447276d8cbe1dad8c4ab69fc6d72e5b36d6)) +* **internal:** fix example formatting ([#508](https://github.com/Finch-API/finch-api-java/issues/508)) ([89c25c1](https://github.com/Finch-API/finch-api-java/commit/89c25c19eca3db5ef766e64e605291d6dad69d05)) +* **internal:** generate more tests ([35fd786](https://github.com/Finch-API/finch-api-java/commit/35fd7864ce86a276116c74475f5654579f5fd7a2)) +* **internal:** make multipart assertions more robust ([f0417a8](https://github.com/Finch-API/finch-api-java/commit/f0417a891f12e01d7040af3ccb07e13f07ca8034)) +* **internal:** make test classes internal ([#495](https://github.com/Finch-API/finch-api-java/issues/495)) ([2048a6a](https://github.com/Finch-API/finch-api-java/commit/2048a6a29711b2436894c0498bcd97c89ce7ac4c)) +* **internal:** reenable warnings as errors ([#485](https://github.com/Finch-API/finch-api-java/issues/485)) ([0d38744](https://github.com/Finch-API/finch-api-java/commit/0d387447276d8cbe1dad8c4ab69fc6d72e5b36d6)) +* **internal:** refactor enum query param serialization ([#503](https://github.com/Finch-API/finch-api-java/issues/503)) ([8894d83](https://github.com/Finch-API/finch-api-java/commit/8894d8307db6b7bdc92319b6f356addec96c64a5)) +* **internal:** refactor query param serialization impl and tests ([#498](https://github.com/Finch-API/finch-api-java/issues/498)) ([6da412b](https://github.com/Finch-API/finch-api-java/commit/6da412b3e388bc9034c4ec7bdfd5579657b39a47)) +* **internal:** refactor some test assertions ([d1b1bd2](https://github.com/Finch-API/finch-api-java/commit/d1b1bd2847f0ffa069f9d9bce5702f093b129797)) +* **internal:** reformat some tests ([#500](https://github.com/Finch-API/finch-api-java/issues/500)) ([35fd786](https://github.com/Finch-API/finch-api-java/commit/35fd7864ce86a276116c74475f5654579f5fd7a2)) +* **internal:** remove unnecessary `assertNotNull` calls ([f0417a8](https://github.com/Finch-API/finch-api-java/commit/f0417a891f12e01d7040af3ccb07e13f07ca8034)) +* **internal:** remove unnecessary import ([#509](https://github.com/Finch-API/finch-api-java/issues/509)) ([4b12e68](https://github.com/Finch-API/finch-api-java/commit/4b12e6826583668726201f446ccb63bd4e97d51c)) +* **internal:** rename `getPathParam` ([#499](https://github.com/Finch-API/finch-api-java/issues/499)) ([d1b1bd2](https://github.com/Finch-API/finch-api-java/commit/d1b1bd2847f0ffa069f9d9bce5702f093b129797)) +* **internal:** reorder some params methodsc ([d1b1bd2](https://github.com/Finch-API/finch-api-java/commit/d1b1bd2847f0ffa069f9d9bce5702f093b129797)) +* **internal:** swap from `getNullable` to `getOptional` ([#528](https://github.com/Finch-API/finch-api-java/issues/528)) ([70033bd](https://github.com/Finch-API/finch-api-java/commit/70033bd2f85bbb1cccefbff8eb86193f912e92c2)) +* **internal:** use `getOrNull` instead of `orElse(null)` ([#484](https://github.com/Finch-API/finch-api-java/issues/484)) ([9c0806b](https://github.com/Finch-API/finch-api-java/commit/9c0806b3134e745134ee74cbeda97d2e80584c57)) +* **tests:** improve enum examples ([#532](https://github.com/Finch-API/finch-api-java/issues/532)) ([775392d](https://github.com/Finch-API/finch-api-java/commit/775392dc621cd9a1f297897b00aba7264c294e2a)) + + +### Documentation + +* add `build` method comments ([#497](https://github.com/Finch-API/finch-api-java/issues/497)) ([d199989](https://github.com/Finch-API/finch-api-java/commit/d199989894e98456e329085b6904bc58f889bae6)) +* add comments to `JsonField` classes ([8b601dc](https://github.com/Finch-API/finch-api-java/commit/8b601dc398296e351a1f0590ef858063fec9f48a)) +* add raw response readme documentation ([#474](https://github.com/Finch-API/finch-api-java/issues/474)) ([81a5824](https://github.com/Finch-API/finch-api-java/commit/81a5824dbff19ae8328a747aed49dc5ea1fbc2c8)) +* deduplicate and refine comments ([#494](https://github.com/Finch-API/finch-api-java/issues/494)) ([651b10e](https://github.com/Finch-API/finch-api-java/commit/651b10e981e1c1e182fce79205176e637930473b)) +* document `JsonValue` construction in readme ([#487](https://github.com/Finch-API/finch-api-java/issues/487)) ([e790ad5](https://github.com/Finch-API/finch-api-java/commit/e790ad57e21491a0edcada3ae2d544f3ae7eb35e)) +* document how to forcibly omit required field ([7989f32](https://github.com/Finch-API/finch-api-java/commit/7989f32f6893b9374514ccda99c88d8ab093bf11)) +* minor readme tweak ([#511](https://github.com/Finch-API/finch-api-java/issues/511)) ([12e8d47](https://github.com/Finch-API/finch-api-java/commit/12e8d474f44c2e32c74eed6beb57a8fa2080de03)) +* note required fields in `builder` javadoc ([#475](https://github.com/Finch-API/finch-api-java/issues/475)) ([2d0c4c8](https://github.com/Finch-API/finch-api-java/commit/2d0c4c8f7d3b629db18937db95415474b10f8bc9)) +* refine comments on multipart params ([#507](https://github.com/Finch-API/finch-api-java/issues/507)) ([f0417a8](https://github.com/Finch-API/finch-api-java/commit/f0417a891f12e01d7040af3ccb07e13f07ca8034)) +* revise readme docs about nested params ([#486](https://github.com/Finch-API/finch-api-java/issues/486)) ([3682e62](https://github.com/Finch-API/finch-api-java/commit/3682e62316dcbac48b8c2a7e3b1df8f19ae5d96e)) +* swap examples used in readme ([#530](https://github.com/Finch-API/finch-api-java/issues/530)) ([7989f32](https://github.com/Finch-API/finch-api-java/commit/7989f32f6893b9374514ccda99c88d8ab093bf11)) +* update readme exception docs ([#510](https://github.com/Finch-API/finch-api-java/issues/510)) ([949341a](https://github.com/Finch-API/finch-api-java/commit/949341a607502df838f4c062d4a4afaaa4bdf2b8)) +* update URLs from stainlessapi.com to stainless.com ([#467](https://github.com/Finch-API/finch-api-java/issues/467)) ([238b853](https://github.com/Finch-API/finch-api-java/commit/238b853b930f203759499a7d9540c35b586a3915)) + ## 4.2.0 (2025-02-27) Full Changelog: [v4.1.0...v4.2.0](https://github.com/Finch-API/finch-api-java/compare/v4.1.0...v4.2.0) diff --git a/README.md b/README.md index a4e73200..e0b9c13b 100644 --- a/README.md +++ b/README.md @@ -2,19 +2,22 @@ -[![Maven Central](https://img.shields.io/maven-central/v/com.tryfinch.api/finch-java)](https://central.sonatype.com/artifact/com.tryfinch.api/finch-java/4.2.0) +[![Maven Central](https://img.shields.io/maven-central/v/com.tryfinch.api/finch-java)](https://central.sonatype.com/artifact/com.tryfinch.api/finch-java/5.0.0) +[![javadoc](https://javadoc.io/badge2/com.tryfinch.api/finch-java/5.0.0/javadoc.svg)](https://javadoc.io/doc/com.tryfinch.api/finch-java/5.0.0) -The Finch Java SDK provides convenient access to the Finch REST API from applications written in Java. +The Finch Java SDK provides convenient access to the [Finch REST API](https://developer.tryfinch.com/) from applications written in Java. The Finch Java SDK is similar to the Finch Kotlin SDK but with minor differences that make it more ergonomic for use in Java, such as `Optional` instead of nullable values, `Stream` instead of `Sequence`, and `CompletableFuture` instead of suspend functions. -It is generated with [Stainless](https://www.stainlessapi.com/). +It is generated with [Stainless](https://www.stainless.com/). -The REST API documentation can be found [in the Finch Documentation Center](https://developer.tryfinch.com/). + + +The REST API documentation can be found on [developer.tryfinch.com](https://developer.tryfinch.com/). Javadocs are also available on [javadoc.io](https://javadoc.io/doc/com.tryfinch.api/finch-java/5.0.0). ---- + ## Installation @@ -23,16 +26,16 @@ The REST API documentation can be found [in the Finch Documentation Center](htt ### Gradle ```kotlin -implementation("com.tryfinch.api:finch-java:4.2.0") +implementation("com.tryfinch.api:finch-java:5.0.0") ``` ### Maven ```xml - com.tryfinch.api - finch-java - 4.2.0 + com.tryfinch.api + finch-java + 5.0.0 ``` @@ -164,22 +167,48 @@ CompletableFuture page = client.hris().directory().l The asynchronous client supports the same options as the synchronous one, except most methods return `CompletableFuture`s. +## Raw responses + +The SDK defines methods that deserialize responses into instances of Java classes. However, these methods don't provide access to the response headers, status code, or the raw response body. + +To access this data, prefix any HTTP method call on a client or service with `withRawResponse()`: + +```java +import com.tryfinch.api.core.http.Headers; +import com.tryfinch.api.core.http.HttpResponseFor; +import com.tryfinch.api.models.HrisDirectoryListPage; +import com.tryfinch.api.models.HrisDirectoryListParams; + +HttpResponseFor page = client.hris().directory().withRawResponse().list(); + +int statusCode = page.statusCode(); +Headers headers = page.headers(); +``` + +You can still deserialize the response into an instance of a Java class if needed: + +```java +import com.tryfinch.api.models.HrisDirectoryListPage; + +HrisDirectoryListPage parsedPage = page.parse(); +``` + ## Error handling The SDK throws custom unchecked exception types: - [`FinchServiceException`](finch-java-core/src/main/kotlin/com/tryfinch/api/errors/FinchServiceException.kt): Base class for HTTP errors. See this table for which exception subclass is thrown for each HTTP status code: - | Status | Exception | - | ------ | ------------------------------- | - | 400 | `BadRequestException` | - | 401 | `AuthenticationException` | - | 403 | `PermissionDeniedException` | - | 404 | `NotFoundException` | - | 422 | `UnprocessableEntityException` | - | 429 | `RateLimitException` | - | 5xx | `InternalServerException` | - | others | `UnexpectedStatusCodeException` | + | Status | Exception | + | ------ | --------------------------------------------------------------------------------------------------------------------------- | + | 400 | [`BadRequestException`](finch-java-core/src/main/kotlin/com/tryfinch/api/errors/BadRequestException.kt) | + | 401 | [`UnauthorizedException`](finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnauthorizedException.kt) | + | 403 | [`PermissionDeniedException`](finch-java-core/src/main/kotlin/com/tryfinch/api/errors/PermissionDeniedException.kt) | + | 404 | [`NotFoundException`](finch-java-core/src/main/kotlin/com/tryfinch/api/errors/NotFoundException.kt) | + | 422 | [`UnprocessableEntityException`](finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnprocessableEntityException.kt) | + | 429 | [`RateLimitException`](finch-java-core/src/main/kotlin/com/tryfinch/api/errors/RateLimitException.kt) | + | 5xx | [`InternalServerException`](finch-java-core/src/main/kotlin/com/tryfinch/api/errors/InternalServerException.kt) | + | others | [`UnexpectedStatusCodeException`](finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnexpectedStatusCodeException.kt) | - [`FinchIoException`](finch-java-core/src/main/kotlin/com/tryfinch/api/errors/FinchIoException.kt): I/O networking errors. @@ -361,9 +390,9 @@ HrisDirectoryListParams params = HrisDirectoryListParams.builder() .build(); ``` -These can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods. You can also set undocumented parameters on nested headers, query params, or body classes using the `putAdditionalProperty` method. These properties can be accessed on the built object later using the `_additionalProperties()` method. +These can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods. -To set a documented parameter or property to an undocumented or not yet supported _value_, pass a [`JsonValue`](finch-java-core/src/main/kotlin/com/tryfinch/api/core/JsonValue.kt) object to its setter: +To set a documented parameter or property to an undocumented or not yet supported _value_, pass a [`JsonValue`](finch-java-core/src/main/kotlin/com/tryfinch/api/core/Values.kt) object to its setter: ```java import com.tryfinch.api.models.HrisDirectoryListParams; @@ -371,6 +400,59 @@ import com.tryfinch.api.models.HrisDirectoryListParams; HrisDirectoryListParams params = HrisDirectoryListParams.builder().build(); ``` +The most straightforward way to create a [`JsonValue`](finch-java-core/src/main/kotlin/com/tryfinch/api/core/Values.kt) is using its `from(...)` method: + +```java +import com.tryfinch.api.core.JsonValue; +import java.util.List; +import java.util.Map; + +// Create primitive JSON values +JsonValue nullValue = JsonValue.from(null); +JsonValue booleanValue = JsonValue.from(true); +JsonValue numberValue = JsonValue.from(42); +JsonValue stringValue = JsonValue.from("Hello World!"); + +// Create a JSON array value equivalent to `["Hello", "World"]` +JsonValue arrayValue = JsonValue.from(List.of( + "Hello", "World" +)); + +// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }` +JsonValue objectValue = JsonValue.from(Map.of( + "a", 1, + "b", 2 +)); + +// Create an arbitrarily nested JSON equivalent to: +// { +// "a": [1, 2], +// "b": [3, 4] +// } +JsonValue complexValue = JsonValue.from(Map.of( + "a", List.of( + 1, 2 + ), + "b", List.of( + 3, 4 + ) +)); +``` + +Normally a `Builder` class's `build` method will throw [`IllegalStateException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html) if any required parameter or property is unset. + +To forcibly omit a required parameter or property, pass [`JsonMissing`](finch-java-core/src/main/kotlin/com/tryfinch/api/core/Values.kt): + +```java +import com.tryfinch.api.core.JsonMissing; +import com.tryfinch.api.models.AccessTokenCreateParams; +import com.tryfinch.api.models.HrisDirectoryListParams; + +HrisDirectoryListParams params = AccessTokenCreateParams.builder() + .code(JsonMissing.of()) + .build(); +``` + ### Response properties To access undocumented response properties, call the `_additionalProperties()` method: diff --git a/SECURITY.md b/SECURITY.md index 6cef554f..b6499508 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,9 +2,9 @@ ## Reporting Security Issues -This SDK is generated by [Stainless Software Inc](http://stainlessapi.com). Stainless takes security seriously, and encourages you to report any security vulnerability promptly so that appropriate action can be taken. +This SDK is generated by [Stainless Software Inc](http://stainless.com). Stainless takes security seriously, and encourages you to report any security vulnerability promptly so that appropriate action can be taken. -To report a security issue, please contact the Stainless team at security@stainlessapi.com. +To report a security issue, please contact the Stainless team at security@stainless.com. ## Responsible Disclosure diff --git a/build.gradle.kts b/build.gradle.kts index 5b66da78..371fde06 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,4 +1,23 @@ +plugins { + id("org.jetbrains.dokka") version "2.0.0" +} + +repositories { + mavenCentral() +} + allprojects { group = "com.tryfinch.api" - version = "4.2.0" // x-release-please-version + version = "5.0.0" // x-release-please-version +} + +subprojects { + apply(plugin = "org.jetbrains.dokka") +} + +// Avoid race conditions between `dokkaJavadocCollector` and `dokkaJavadocJar` tasks +tasks.named("dokkaJavadocCollector").configure { + subprojects.flatMap { it.tasks } + .filter { it.project.name != "finch-java" && it.name == "dokkaJavadocJar" } + .forEach { mustRunAfter(it) } } diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index d1ed374d..778c89de 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -1,6 +1,6 @@ plugins { `kotlin-dsl` - kotlin("jvm") version "2.1.10" + kotlin("jvm") version "1.9.20" id("com.vanniktech.maven.publish") version "0.28.0" } @@ -11,6 +11,6 @@ repositories { dependencies { implementation("com.diffplug.spotless:spotless-plugin-gradle:7.0.2") - implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:2.1.10") + implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.20") implementation("com.vanniktech:gradle-maven-publish-plugin:0.28.0") } diff --git a/buildSrc/src/main/kotlin/finch.java.gradle.kts b/buildSrc/src/main/kotlin/finch.java.gradle.kts index 597b6e80..e39d9ac6 100644 --- a/buildSrc/src/main/kotlin/finch.java.gradle.kts +++ b/buildSrc/src/main/kotlin/finch.java.gradle.kts @@ -23,6 +23,9 @@ java { toolchain { languageVersion.set(JavaLanguageVersion.of(17)) } + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 } tasks.withType().configureEach { diff --git a/buildSrc/src/main/kotlin/finch.kotlin.gradle.kts b/buildSrc/src/main/kotlin/finch.kotlin.gradle.kts index 9bdebacd..2fcf511b 100644 --- a/buildSrc/src/main/kotlin/finch.kotlin.gradle.kts +++ b/buildSrc/src/main/kotlin/finch.kotlin.gradle.kts @@ -1,6 +1,6 @@ import com.diffplug.gradle.spotless.SpotlessExtension import org.jetbrains.kotlin.gradle.dsl.JvmTarget -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import org.jetbrains.kotlin.gradle.dsl.KotlinVersion plugins { id("finch.java") @@ -11,6 +11,20 @@ kotlin { jvmToolchain { languageVersion.set(JavaLanguageVersion.of(17)) } + + compilerOptions { + freeCompilerArgs = listOf( + "-Xjvm-default=all", + "-Xjdk-release=1.8", + // Suppress deprecation warnings because we may still reference and test deprecated members. + // TODO: Replace with `-Xsuppress-warning=DEPRECATION` once we use Kotlin compiler 2.1.0+. + "-nowarn", + ) + jvmTarget.set(JvmTarget.JVM_1_8) + languageVersion.set(KotlinVersion.KOTLIN_1_8) + apiVersion.set(KotlinVersion.KOTLIN_1_8) + coreLibrariesVersion = "1.8.0" + } } configure { @@ -20,18 +34,6 @@ configure { } } -tasks.withType().configureEach { - compilerOptions { - freeCompilerArgs = listOf( - "-Xjvm-default=all", - "-Xjdk-release=1.8", - // Suppress deprecation warnings because we may still reference and test deprecated members. - "-Xsuppress-warning=DEPRECATION" - ) - jvmTarget.set(JvmTarget.JVM_1_8) - } -} - // Run tests in parallel to some degree. tasks.withType().configureEach { maxParallelForks = (Runtime.getRuntime().availableProcessors() / 2).coerceAtLeast(1) diff --git a/buildSrc/src/main/kotlin/finch.publish.gradle.kts b/buildSrc/src/main/kotlin/finch.publish.gradle.kts index e193185b..814dfc3e 100644 --- a/buildSrc/src/main/kotlin/finch.publish.gradle.kts +++ b/buildSrc/src/main/kotlin/finch.publish.gradle.kts @@ -1,3 +1,5 @@ +import com.vanniktech.maven.publish.JavadocJar +import com.vanniktech.maven.publish.KotlinJvm import com.vanniktech.maven.publish.MavenPublishBaseExtension import com.vanniktech.maven.publish.SonatypeHost @@ -19,6 +21,12 @@ configure { publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL) coordinates(project.group.toString(), project.name, project.version.toString()) + configure( + KotlinJvm( + javadocJar = JavadocJar.Dokka("dokkaJavadoc"), + sourcesJar = true, + ) + ) pom { name.set("API Reference") diff --git a/finch-java-client-okhttp/src/main/kotlin/com/tryfinch/api/client/okhttp/FinchOkHttpClient.kt b/finch-java-client-okhttp/src/main/kotlin/com/tryfinch/api/client/okhttp/FinchOkHttpClient.kt index 9cb8ed19..3e365dbe 100644 --- a/finch-java-client-okhttp/src/main/kotlin/com/tryfinch/api/client/okhttp/FinchOkHttpClient.kt +++ b/finch-java-client-okhttp/src/main/kotlin/com/tryfinch/api/client/okhttp/FinchOkHttpClient.kt @@ -6,17 +6,20 @@ import com.fasterxml.jackson.databind.json.JsonMapper import com.tryfinch.api.client.FinchClient import com.tryfinch.api.client.FinchClientImpl import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.Timeout import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams import java.net.Proxy import java.time.Clock import java.time.Duration import java.util.Optional +import kotlin.jvm.optionals.getOrNull class FinchOkHttpClient private constructor() { companion object { + /** Returns a mutable builder for constructing an instance of [FinchOkHttpClient]. */ @JvmStatic fun builder() = Builder() @JvmStatic fun fromEnv(): FinchClient = builder().fromEnv().build() @@ -27,8 +30,7 @@ class FinchOkHttpClient private constructor() { private var clientOptions: ClientOptions.Builder = ClientOptions.builder() private var baseUrl: String = ClientOptions.PRODUCTION_URL - // The default timeout for the client is 1 minute. - private var timeout: Duration = Duration.ofSeconds(60) + private var timeout: Timeout = Timeout.default() private var proxy: Proxy? = null fun baseUrl(baseUrl: String) = apply { @@ -36,6 +38,17 @@ class FinchOkHttpClient private constructor() { this.baseUrl = baseUrl } + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee + * that the SDK will work correctly when using an incompatible Jackson version. + */ + fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { + clientOptions.checkJacksonVersionCompatibility(checkJacksonVersionCompatibility) + } + fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } fun clock(clock: Clock) = apply { clientOptions.clock(clock) } @@ -120,7 +133,19 @@ class FinchOkHttpClient private constructor() { clientOptions.removeAllQueryParams(keys) } - fun timeout(timeout: Duration) = apply { this.timeout = timeout } + fun timeout(timeout: Timeout) = apply { + clientOptions.timeout(timeout) + this.timeout = timeout + } + + /** + * Sets the maximum time allowed for a complete HTTP call, not including retries. + * + * See [Timeout.request] for more details. + * + * For fine-grained control, pass a [Timeout] object. + */ + fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } @@ -132,25 +157,34 @@ class FinchOkHttpClient private constructor() { fun accessToken(accessToken: String?) = apply { clientOptions.accessToken(accessToken) } - fun accessToken(accessToken: Optional) = accessToken(accessToken.orElse(null)) + /** Alias for calling [Builder.accessToken] with `accessToken.orElse(null)`. */ + fun accessToken(accessToken: Optional) = accessToken(accessToken.getOrNull()) fun clientId(clientId: String?) = apply { clientOptions.clientId(clientId) } - fun clientId(clientId: Optional) = clientId(clientId.orElse(null)) + /** Alias for calling [Builder.clientId] with `clientId.orElse(null)`. */ + fun clientId(clientId: Optional) = clientId(clientId.getOrNull()) fun clientSecret(clientSecret: String?) = apply { clientOptions.clientSecret(clientSecret) } - fun clientSecret(clientSecret: Optional) = clientSecret(clientSecret.orElse(null)) + /** Alias for calling [Builder.clientSecret] with `clientSecret.orElse(null)`. */ + fun clientSecret(clientSecret: Optional) = clientSecret(clientSecret.getOrNull()) fun webhookSecret(webhookSecret: String?) = apply { clientOptions.webhookSecret(webhookSecret) } + /** Alias for calling [Builder.webhookSecret] with `webhookSecret.orElse(null)`. */ fun webhookSecret(webhookSecret: Optional) = - webhookSecret(webhookSecret.orElse(null)) + webhookSecret(webhookSecret.getOrNull()) fun fromEnv() = apply { clientOptions.fromEnv() } + /** + * Returns an immutable instance of [FinchClient]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): FinchClient = FinchClientImpl( clientOptions diff --git a/finch-java-client-okhttp/src/main/kotlin/com/tryfinch/api/client/okhttp/FinchOkHttpClientAsync.kt b/finch-java-client-okhttp/src/main/kotlin/com/tryfinch/api/client/okhttp/FinchOkHttpClientAsync.kt index 29934ab4..0a25d955 100644 --- a/finch-java-client-okhttp/src/main/kotlin/com/tryfinch/api/client/okhttp/FinchOkHttpClientAsync.kt +++ b/finch-java-client-okhttp/src/main/kotlin/com/tryfinch/api/client/okhttp/FinchOkHttpClientAsync.kt @@ -6,17 +6,20 @@ import com.fasterxml.jackson.databind.json.JsonMapper import com.tryfinch.api.client.FinchClientAsync import com.tryfinch.api.client.FinchClientAsyncImpl import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.Timeout import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams import java.net.Proxy import java.time.Clock import java.time.Duration import java.util.Optional +import kotlin.jvm.optionals.getOrNull class FinchOkHttpClientAsync private constructor() { companion object { + /** Returns a mutable builder for constructing an instance of [FinchOkHttpClientAsync]. */ @JvmStatic fun builder() = Builder() @JvmStatic fun fromEnv(): FinchClientAsync = builder().fromEnv().build() @@ -27,8 +30,7 @@ class FinchOkHttpClientAsync private constructor() { private var clientOptions: ClientOptions.Builder = ClientOptions.builder() private var baseUrl: String = ClientOptions.PRODUCTION_URL - // The default timeout for the client is 1 minute. - private var timeout: Duration = Duration.ofSeconds(60) + private var timeout: Timeout = Timeout.default() private var proxy: Proxy? = null fun baseUrl(baseUrl: String) = apply { @@ -36,6 +38,17 @@ class FinchOkHttpClientAsync private constructor() { this.baseUrl = baseUrl } + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee + * that the SDK will work correctly when using an incompatible Jackson version. + */ + fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { + clientOptions.checkJacksonVersionCompatibility(checkJacksonVersionCompatibility) + } + fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } fun clock(clock: Clock) = apply { clientOptions.clock(clock) } @@ -120,7 +133,19 @@ class FinchOkHttpClientAsync private constructor() { clientOptions.removeAllQueryParams(keys) } - fun timeout(timeout: Duration) = apply { this.timeout = timeout } + fun timeout(timeout: Timeout) = apply { + clientOptions.timeout(timeout) + this.timeout = timeout + } + + /** + * Sets the maximum time allowed for a complete HTTP call, not including retries. + * + * See [Timeout.request] for more details. + * + * For fine-grained control, pass a [Timeout] object. + */ + fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } @@ -132,25 +157,34 @@ class FinchOkHttpClientAsync private constructor() { fun accessToken(accessToken: String?) = apply { clientOptions.accessToken(accessToken) } - fun accessToken(accessToken: Optional) = accessToken(accessToken.orElse(null)) + /** Alias for calling [Builder.accessToken] with `accessToken.orElse(null)`. */ + fun accessToken(accessToken: Optional) = accessToken(accessToken.getOrNull()) fun clientId(clientId: String?) = apply { clientOptions.clientId(clientId) } - fun clientId(clientId: Optional) = clientId(clientId.orElse(null)) + /** Alias for calling [Builder.clientId] with `clientId.orElse(null)`. */ + fun clientId(clientId: Optional) = clientId(clientId.getOrNull()) fun clientSecret(clientSecret: String?) = apply { clientOptions.clientSecret(clientSecret) } - fun clientSecret(clientSecret: Optional) = clientSecret(clientSecret.orElse(null)) + /** Alias for calling [Builder.clientSecret] with `clientSecret.orElse(null)`. */ + fun clientSecret(clientSecret: Optional) = clientSecret(clientSecret.getOrNull()) fun webhookSecret(webhookSecret: String?) = apply { clientOptions.webhookSecret(webhookSecret) } + /** Alias for calling [Builder.webhookSecret] with `webhookSecret.orElse(null)`. */ fun webhookSecret(webhookSecret: Optional) = - webhookSecret(webhookSecret.orElse(null)) + webhookSecret(webhookSecret.getOrNull()) fun fromEnv() = apply { clientOptions.fromEnv() } + /** + * Returns an immutable instance of [FinchClientAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): FinchClientAsync = FinchClientAsyncImpl( clientOptions diff --git a/finch-java-client-okhttp/src/main/kotlin/com/tryfinch/api/client/okhttp/OkHttpClient.kt b/finch-java-client-okhttp/src/main/kotlin/com/tryfinch/api/client/okhttp/OkHttpClient.kt index 7c59fad7..be523572 100644 --- a/finch-java-client-okhttp/src/main/kotlin/com/tryfinch/api/client/okhttp/OkHttpClient.kt +++ b/finch-java-client-okhttp/src/main/kotlin/com/tryfinch/api/client/okhttp/OkHttpClient.kt @@ -1,6 +1,7 @@ package com.tryfinch.api.client.okhttp import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.Timeout import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.HttpClient @@ -88,13 +89,12 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val ) } - val timeout = requestOptions.timeout - if (timeout != null) { + requestOptions.timeout?.let { clientBuilder - .connectTimeout(timeout) - .readTimeout(timeout) - .writeTimeout(timeout) - .callTimeout(if (timeout.seconds == 0L) timeout else timeout.plusSeconds(30)) + .connectTimeout(it.connect()) + .readTimeout(it.read()) + .writeTimeout(it.write()) + .callTimeout(it.request()) } val client = clientBuilder.build() @@ -195,23 +195,24 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val class Builder internal constructor() { private var baseUrl: HttpUrl? = null - // The default timeout is 1 minute. - private var timeout: Duration = Duration.ofSeconds(60) + private var timeout: Timeout = Timeout.default() private var proxy: Proxy? = null fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl.toHttpUrl() } - fun timeout(timeout: Duration) = apply { this.timeout = timeout } + fun timeout(timeout: Timeout) = apply { this.timeout = timeout } + + fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } fun build(): OkHttpClient = OkHttpClient( okhttp3.OkHttpClient.Builder() - .connectTimeout(timeout) - .readTimeout(timeout) - .writeTimeout(timeout) - .callTimeout(if (timeout.seconds == 0L) timeout else timeout.plusSeconds(30)) + .connectTimeout(timeout.connect()) + .readTimeout(timeout.read()) + .writeTimeout(timeout.write()) + .callTimeout(timeout.request()) .proxy(proxy) .build(), checkRequired("baseUrl", baseUrl), diff --git a/finch-java-core/build.gradle.kts b/finch-java-core/build.gradle.kts index af4554e6..cc2d57aa 100644 --- a/finch-java-core/build.gradle.kts +++ b/finch-java-core/build.gradle.kts @@ -3,9 +3,23 @@ plugins { id("finch.publish") } +configurations.all { + resolutionStrategy { + // Compile and test against a lower Jackson version to ensure we're compatible with it. + // We publish with a higher version (see below) to ensure users depend on a secure version by default. + force("com.fasterxml.jackson.core:jackson-core:2.13.4") + force("com.fasterxml.jackson.core:jackson-databind:2.13.4") + force("com.fasterxml.jackson.core:jackson-annotations:2.13.4") + force("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.13.4") + force("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.4") + force("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.4") + } +} + dependencies { api("com.fasterxml.jackson.core:jackson-core:2.18.1") api("com.fasterxml.jackson.core:jackson-databind:2.18.1") + api("com.google.errorprone:error_prone_annotations:2.33.0") implementation("com.fasterxml.jackson.core:jackson-annotations:2.18.1") implementation("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.18.1") @@ -20,6 +34,7 @@ dependencies { testImplementation("org.assertj:assertj-core:3.25.3") testImplementation("org.junit.jupiter:junit-jupiter-api:5.9.3") testImplementation("org.junit.jupiter:junit-jupiter-params:5.9.3") + testImplementation("org.junit-pioneer:junit-pioneer:1.9.1") testImplementation("org.mockito:mockito-core:5.14.2") testImplementation("org.mockito:mockito-junit-jupiter:5.14.2") testImplementation("org.mockito.kotlin:mockito-kotlin:4.1.0") diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClient.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClient.kt index bf99f84a..4d6662df 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClient.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClient.kt @@ -38,6 +38,11 @@ interface FinchClient { */ fun async(): FinchClientAsync + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun accessTokens(): AccessTokenService fun hris(): HrisService @@ -100,4 +105,26 @@ interface FinchClient { * method. */ fun close() + + /** A view of [FinchClient] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun accessTokens(): AccessTokenService.WithRawResponse + + fun hris(): HrisService.WithRawResponse + + fun providers(): ProviderService.WithRawResponse + + fun account(): AccountService.WithRawResponse + + fun requestForwarding(): RequestForwardingService.WithRawResponse + + fun jobs(): JobService.WithRawResponse + + fun sandbox(): SandboxService.WithRawResponse + + fun payroll(): PayrollService.WithRawResponse + + fun connect(): ConnectService.WithRawResponse + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClientAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClientAsync.kt index e20d730b..d829a593 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClientAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClientAsync.kt @@ -39,6 +39,11 @@ interface FinchClientAsync { */ fun sync(): FinchClient + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun accessTokens(): AccessTokenServiceAsync fun hris(): HrisServiceAsync @@ -101,4 +106,26 @@ interface FinchClientAsync { * method. */ fun close() + + /** A view of [FinchClientAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun accessTokens(): AccessTokenServiceAsync.WithRawResponse + + fun hris(): HrisServiceAsync.WithRawResponse + + fun providers(): ProviderServiceAsync.WithRawResponse + + fun account(): AccountServiceAsync.WithRawResponse + + fun requestForwarding(): RequestForwardingServiceAsync.WithRawResponse + + fun jobs(): JobServiceAsync.WithRawResponse + + fun sandbox(): SandboxServiceAsync.WithRawResponse + + fun payroll(): PayrollServiceAsync.WithRawResponse + + fun connect(): ConnectServiceAsync.WithRawResponse + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClientAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClientAsyncImpl.kt index 1a33fcc6..23a0f4e0 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClientAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClientAsyncImpl.kt @@ -4,6 +4,7 @@ package com.tryfinch.api.client import com.fasterxml.jackson.annotation.JsonProperty import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.getPackageVersion import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -11,8 +12,7 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json -import com.tryfinch.api.errors.FinchError +import com.tryfinch.api.core.http.json import com.tryfinch.api.errors.FinchException import com.tryfinch.api.models.* import com.tryfinch.api.services.async.AccessTokenServiceAsync @@ -40,7 +40,7 @@ import java.util.concurrent.CompletableFuture class FinchClientAsyncImpl(private val clientOptions: ClientOptions) : FinchClientAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val clientOptionsWithUserAgent = if (clientOptions.headers.names().contains("User-Agent")) clientOptions @@ -52,6 +52,10 @@ class FinchClientAsyncImpl(private val clientOptions: ClientOptions) : FinchClie private val sync: FinchClient by lazy { FinchClientImpl(clientOptions) } + private val withRawResponse: FinchClientAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val accessTokens: AccessTokenServiceAsync by lazy { AccessTokenServiceAsyncImpl(clientOptionsWithUserAgent) } @@ -93,6 +97,8 @@ class FinchClientAsyncImpl(private val clientOptions: ClientOptions) : FinchClie override fun sync(): FinchClient = sync + override fun withRawResponse(): FinchClientAsync.WithRawResponse = withRawResponse + override fun accessTokens(): AccessTokenServiceAsync = accessTokens override fun hris(): HrisServiceAsync = hris @@ -121,10 +127,10 @@ class FinchClientAsyncImpl(private val clientOptions: ClientOptions) : FinchClie code: String, redirectUri: String?, ): CompletableFuture { - if (clientOptions.clientId == null) { + if (!clientOptions.clientId().isPresent) { throw FinchException("clientId must be set in order to call getAccessToken") } - if (clientOptions.clientSecret == null) { + if (!clientOptions.clientSecret().isPresent) { throw FinchException("clientSecret must be set in order to call getAccessToken") } val request = @@ -144,11 +150,11 @@ class FinchClientAsyncImpl(private val clientOptions: ClientOptions) : FinchClie } override fun getAuthUrl(products: String, redirectUri: String, sandbox: Boolean): String { - if (clientOptions.clientId == null) { + if (!clientOptions.clientId().isPresent) { throw FinchException("Expected the clientId to be set in order to call getAuthUrl") } return "https://connect.tryfinch.com/authorize" + - "?client_id=${URLEncoder.encode(clientOptions.clientId, Charsets.UTF_8.name())}" + + "?client_id=${URLEncoder.encode(clientOptions.clientId().get(), Charsets.UTF_8.name())}" + "&products=${URLEncoder.encode(products, Charsets.UTF_8.name())}" + "&redirect_uri=${URLEncoder.encode(redirectUri, Charsets.UTF_8.name())}" + "&sandbox=${if (sandbox) "true" else "false"}" @@ -162,9 +168,9 @@ class FinchClientAsyncImpl(private val clientOptions: ClientOptions) : FinchClie .clock(clientOptions.clock) .baseUrl(clientOptions.baseUrl) .accessToken(accessToken) - .apply { clientOptions.clientId?.let(::clientId) } - .apply { clientOptions.clientSecret?.let(::clientSecret) } - .apply { clientOptions.webhookSecret?.let(::webhookSecret) } + .clientId(clientOptions.clientId()) + .clientSecret(clientOptions.clientSecret()) + .webhookSecret(clientOptions.webhookSecret()) .headers(clientOptions.headers) .responseValidation(clientOptions.responseValidation) .build() @@ -172,21 +178,80 @@ class FinchClientAsyncImpl(private val clientOptions: ClientOptions) : FinchClie } private data class GetAccessTokenParams( - @JsonProperty("client_id") val clientId: String, - @JsonProperty("client_secret") val clientSecret: String, - @JsonProperty("code") val code: String, - @JsonProperty("redirect_uri") val redirectUri: String?, + @get:JsonProperty("client_id") val clientId: String, + @get:JsonProperty("client_secret") val clientSecret: String, + @get:JsonProperty("code") val code: String, + @get:JsonProperty("redirect_uri") val redirectUri: String?, ) private data class GetAccessTokenResponse( - @JsonProperty("access_token") val accessToken: String, - @JsonProperty("account_id") val accountId: String, - @JsonProperty("client_type") val clientType: String, - @JsonProperty("company_id") val companyId: String, - @JsonProperty("connection_type") val connectionType: String, - @JsonProperty("products") val products: List, - @JsonProperty("provider_id") val providerId: String, + @get:JsonProperty("access_token") val accessToken: String, + @get:JsonProperty("account_id") val accountId: String, + @get:JsonProperty("client_type") val clientType: String, + @get:JsonProperty("company_id") val companyId: String, + @get:JsonProperty("connection_type") val connectionType: String, + @get:JsonProperty("products") val products: List, + @get:JsonProperty("provider_id") val providerId: String, ) override fun close() = clientOptions.httpClient.close() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + FinchClientAsync.WithRawResponse { + + private val accessTokens: AccessTokenServiceAsync.WithRawResponse by lazy { + AccessTokenServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val hris: HrisServiceAsync.WithRawResponse by lazy { + HrisServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val providers: ProviderServiceAsync.WithRawResponse by lazy { + ProviderServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val account: AccountServiceAsync.WithRawResponse by lazy { + AccountServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val requestForwarding: RequestForwardingServiceAsync.WithRawResponse by lazy { + RequestForwardingServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val jobs: JobServiceAsync.WithRawResponse by lazy { + JobServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val sandbox: SandboxServiceAsync.WithRawResponse by lazy { + SandboxServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val payroll: PayrollServiceAsync.WithRawResponse by lazy { + PayrollServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val connect: ConnectServiceAsync.WithRawResponse by lazy { + ConnectServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun accessTokens(): AccessTokenServiceAsync.WithRawResponse = accessTokens + + override fun hris(): HrisServiceAsync.WithRawResponse = hris + + override fun providers(): ProviderServiceAsync.WithRawResponse = providers + + override fun account(): AccountServiceAsync.WithRawResponse = account + + override fun requestForwarding(): RequestForwardingServiceAsync.WithRawResponse = + requestForwarding + + override fun jobs(): JobServiceAsync.WithRawResponse = jobs + + override fun sandbox(): SandboxServiceAsync.WithRawResponse = sandbox + + override fun payroll(): PayrollServiceAsync.WithRawResponse = payroll + + override fun connect(): ConnectServiceAsync.WithRawResponse = connect + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClientImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClientImpl.kt index 3f10b2e8..766d1631 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClientImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/client/FinchClientImpl.kt @@ -4,6 +4,7 @@ package com.tryfinch.api.client import com.fasterxml.jackson.annotation.JsonProperty import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.getPackageVersion import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -11,8 +12,7 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json -import com.tryfinch.api.errors.FinchError +import com.tryfinch.api.core.http.json import com.tryfinch.api.errors.FinchException import com.tryfinch.api.models.* import com.tryfinch.api.services.blocking.AccessTokenService @@ -39,7 +39,7 @@ import java.net.URLEncoder class FinchClientImpl(private val clientOptions: ClientOptions) : FinchClient { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) private val clientOptionsWithUserAgent = if (clientOptions.headers.names().contains("User-Agent")) clientOptions @@ -51,6 +51,10 @@ class FinchClientImpl(private val clientOptions: ClientOptions) : FinchClient { private val async: FinchClientAsync by lazy { FinchClientAsyncImpl(clientOptions) } + private val withRawResponse: FinchClient.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val accessTokens: AccessTokenService by lazy { AccessTokenServiceImpl(clientOptionsWithUserAgent) } @@ -82,6 +86,8 @@ class FinchClientImpl(private val clientOptions: ClientOptions) : FinchClient { override fun async(): FinchClientAsync = async + override fun withRawResponse(): FinchClient.WithRawResponse = withRawResponse + override fun accessTokens(): AccessTokenService = accessTokens override fun hris(): HrisService = hris @@ -110,10 +116,10 @@ class FinchClientImpl(private val clientOptions: ClientOptions) : FinchClient { code: String, redirectUri: String?, ): String { - if (clientOptions.clientId == null) { + if (!clientOptions.clientId().isPresent) { throw FinchException("clientId must be set in order to call getAccessToken") } - if (clientOptions.clientSecret == null) { + if (!clientOptions.clientSecret().isPresent) { throw FinchException("clientSecret must be set in order to call getAccessToken") } val request = @@ -133,11 +139,11 @@ class FinchClientImpl(private val clientOptions: ClientOptions) : FinchClient { } override fun getAuthUrl(products: String, redirectUri: String, sandbox: Boolean): String { - if (clientOptions.clientId == null) { + if (!clientOptions.clientId().isPresent) { throw FinchException("Expected the clientId to be set in order to call getAuthUrl") } return "https://connect.tryfinch.com/authorize" + - "?client_id=${URLEncoder.encode(clientOptions.clientId, Charsets.UTF_8.name())}" + + "?client_id=${URLEncoder.encode(clientOptions.clientId().get(), Charsets.UTF_8.name())}" + "&products=${URLEncoder.encode(products, Charsets.UTF_8.name())}" + "&redirect_uri=${URLEncoder.encode(redirectUri, Charsets.UTF_8.name())}" + "&sandbox=${if (sandbox) "true" else "false"}" @@ -151,9 +157,9 @@ class FinchClientImpl(private val clientOptions: ClientOptions) : FinchClient { .clock(clientOptions.clock) .baseUrl(clientOptions.baseUrl) .accessToken(accessToken) - .apply { clientOptions.clientId?.let(::clientId) } - .apply { clientOptions.clientSecret?.let(::clientSecret) } - .apply { clientOptions.webhookSecret?.let(::webhookSecret) } + .clientId(clientOptions.clientId()) + .clientSecret(clientOptions.clientSecret()) + .webhookSecret(clientOptions.webhookSecret()) .headers(clientOptions.headers) .responseValidation(clientOptions.responseValidation) .build() @@ -161,21 +167,80 @@ class FinchClientImpl(private val clientOptions: ClientOptions) : FinchClient { } private data class GetAccessTokenParams( - @JsonProperty("client_id") val clientId: String, - @JsonProperty("client_secret") val clientSecret: String, - @JsonProperty("code") val code: String, - @JsonProperty("redirect_uri") val redirectUri: String?, + @get:JsonProperty("client_id") val clientId: String, + @get:JsonProperty("client_secret") val clientSecret: String, + @get:JsonProperty("code") val code: String, + @get:JsonProperty("redirect_uri") val redirectUri: String?, ) private data class GetAccessTokenResponse( - @JsonProperty("access_token") val accessToken: String, - @JsonProperty("account_id") val accountId: String, - @JsonProperty("client_type") val clientType: String, - @JsonProperty("company_id") val companyId: String, - @JsonProperty("connection_type") val connectionType: String, - @JsonProperty("products") val products: List, - @JsonProperty("provider_id") val providerId: String, + @get:JsonProperty("access_token") val accessToken: String, + @get:JsonProperty("account_id") val accountId: String, + @get:JsonProperty("client_type") val clientType: String, + @get:JsonProperty("company_id") val companyId: String, + @get:JsonProperty("connection_type") val connectionType: String, + @get:JsonProperty("products") val products: List, + @get:JsonProperty("provider_id") val providerId: String, ) override fun close() = clientOptions.httpClient.close() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + FinchClient.WithRawResponse { + + private val accessTokens: AccessTokenService.WithRawResponse by lazy { + AccessTokenServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val hris: HrisService.WithRawResponse by lazy { + HrisServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val providers: ProviderService.WithRawResponse by lazy { + ProviderServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val account: AccountService.WithRawResponse by lazy { + AccountServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val requestForwarding: RequestForwardingService.WithRawResponse by lazy { + RequestForwardingServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val jobs: JobService.WithRawResponse by lazy { + JobServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val sandbox: SandboxService.WithRawResponse by lazy { + SandboxServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val payroll: PayrollService.WithRawResponse by lazy { + PayrollServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val connect: ConnectService.WithRawResponse by lazy { + ConnectServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun accessTokens(): AccessTokenService.WithRawResponse = accessTokens + + override fun hris(): HrisService.WithRawResponse = hris + + override fun providers(): ProviderService.WithRawResponse = providers + + override fun account(): AccountService.WithRawResponse = account + + override fun requestForwarding(): RequestForwardingService.WithRawResponse = + requestForwarding + + override fun jobs(): JobService.WithRawResponse = jobs + + override fun sandbox(): SandboxService.WithRawResponse = sandbox + + override fun payroll(): PayrollService.WithRawResponse = payroll + + override fun connect(): ConnectService.WithRawResponse = connect + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/BaseDeserializer.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/BaseDeserializer.kt index c850405c..315d2cb2 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/BaseDeserializer.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/BaseDeserializer.kt @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.BeanProperty import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JavaType import com.fasterxml.jackson.databind.JsonDeserializer -import com.fasterxml.jackson.databind.JsonMappingException import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.deser.ContextualDeserializer import com.fasterxml.jackson.databind.deser.std.StdDeserializer @@ -29,31 +28,17 @@ abstract class BaseDeserializer(type: KClass) : protected abstract fun ObjectCodec.deserialize(node: JsonNode): T - protected fun ObjectCodec.tryDeserialize( - node: JsonNode, - type: TypeReference, - validate: (T) -> Unit = {}, - ): T? { - return try { - readValue(treeAsTokens(node), type).apply(validate) - } catch (e: JsonMappingException) { - null - } catch (e: RuntimeException) { + protected fun ObjectCodec.tryDeserialize(node: JsonNode, type: TypeReference): T? = + try { + readValue(treeAsTokens(node), type) + } catch (e: Exception) { null } - } - protected fun ObjectCodec.tryDeserialize( - node: JsonNode, - type: JavaType, - validate: (T) -> Unit = {}, - ): T? { - return try { - readValue(treeAsTokens(node), type).apply(validate) - } catch (e: JsonMappingException) { - null - } catch (e: RuntimeException) { + protected fun ObjectCodec.tryDeserialize(node: JsonNode, type: JavaType): T? = + try { + readValue(treeAsTokens(node), type) + } catch (e: Exception) { null } - } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Check.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Check.kt index 38ad8b3e..5918fb36 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Check.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Check.kt @@ -2,9 +2,24 @@ package com.tryfinch.api.core +import com.fasterxml.jackson.core.Version +import com.fasterxml.jackson.core.util.VersionUtil + fun checkRequired(name: String, value: T?): T = checkNotNull(value) { "`$name` is required, but was not set" } +@JvmSynthetic +internal fun checkKnown(name: String, value: JsonField): T = + value.asKnown().orElseThrow { + IllegalStateException("`$name` is not a known type: ${value.javaClass.simpleName}") + } + +@JvmSynthetic +internal fun checkKnown(name: String, value: MultipartField): T = + value.value.asKnown().orElseThrow { + IllegalStateException("`$name` is not a known type: ${value.javaClass.simpleName}") + } + @JvmSynthetic internal fun checkLength(name: String, value: String, length: Int): String = value.also { @@ -27,3 +42,46 @@ internal fun checkMaxLength(name: String, value: String, maxLength: Int): String "`$name` must have at most length $maxLength, but was ${it.length}" } } + +@JvmSynthetic +internal fun checkJacksonVersionCompatibility() { + val incompatibleJacksonVersions = + RUNTIME_JACKSON_VERSIONS.mapNotNull { + when { + it.majorVersion != MINIMUM_JACKSON_VERSION.majorVersion -> + it to "incompatible major version" + it.minorVersion < MINIMUM_JACKSON_VERSION.minorVersion -> + it to "minor version too low" + it.minorVersion == MINIMUM_JACKSON_VERSION.minorVersion && + it.patchLevel < MINIMUM_JACKSON_VERSION.patchLevel -> + it to "patch version too low" + else -> null + } + } + check(incompatibleJacksonVersions.isEmpty()) { + """ +This SDK depends on Jackson version $MINIMUM_JACKSON_VERSION, but the following incompatible Jackson versions were detected at runtime: + +${incompatibleJacksonVersions.asSequence().map { (version, incompatibilityReason) -> + "- `${version.toFullString().replace("/", ":")}` ($incompatibilityReason)" +}.joinToString("\n")} + +This can happen if you are either: +1. Directly depending on different Jackson versions +2. Depending on some library that depends on different Jackson versions, potentially transitively + +Double-check that you are depending on compatible Jackson versions. + """ + .trimIndent() + } +} + +private val MINIMUM_JACKSON_VERSION: Version = VersionUtil.parseVersion("2.13.4", null, null) +private val RUNTIME_JACKSON_VERSIONS: List = + listOf( + com.fasterxml.jackson.core.json.PackageVersion.VERSION, + com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION, + com.fasterxml.jackson.datatype.jdk8.PackageVersion.VERSION, + com.fasterxml.jackson.datatype.jsr310.PackageVersion.VERSION, + com.fasterxml.jackson.module.kotlin.PackageVersion.VERSION, + ) diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/ClientOptions.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/ClientOptions.kt index f34021de..ee2132fe 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/ClientOptions.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/ClientOptions.kt @@ -11,30 +11,55 @@ import com.tryfinch.api.core.http.RetryingHttpClient import java.time.Clock import java.util.Base64 import java.util.Optional +import kotlin.jvm.optionals.getOrNull class ClientOptions private constructor( private val originalHttpClient: HttpClient, @get:JvmName("httpClient") val httpClient: HttpClient, + @get:JvmName("checkJacksonVersionCompatibility") val checkJacksonVersionCompatibility: Boolean, @get:JvmName("jsonMapper") val jsonMapper: JsonMapper, @get:JvmName("clock") val clock: Clock, @get:JvmName("baseUrl") val baseUrl: String, @get:JvmName("headers") val headers: Headers, @get:JvmName("queryParams") val queryParams: QueryParams, @get:JvmName("responseValidation") val responseValidation: Boolean, + @get:JvmName("timeout") val timeout: Timeout, @get:JvmName("maxRetries") val maxRetries: Int, - @get:JvmName("accessToken") val accessToken: String?, - @get:JvmName("clientId") val clientId: String?, - @get:JvmName("clientSecret") val clientSecret: String?, - @get:JvmName("webhookSecret") val webhookSecret: String?, + private val accessToken: String?, + private val clientId: String?, + private val clientSecret: String?, + private val webhookSecret: String?, ) { + init { + if (checkJacksonVersionCompatibility) { + checkJacksonVersionCompatibility() + } + } + + fun accessToken(): Optional = Optional.ofNullable(accessToken) + + fun clientId(): Optional = Optional.ofNullable(clientId) + + fun clientSecret(): Optional = Optional.ofNullable(clientSecret) + + fun webhookSecret(): Optional = Optional.ofNullable(webhookSecret) + fun toBuilder() = Builder().from(this) companion object { const val PRODUCTION_URL = "https://api.tryfinch.com" + /** + * Returns a mutable builder for constructing an instance of [ClientOptions]. + * + * The following fields are required: + * ```java + * .httpClient() + * ``` + */ @JvmStatic fun builder() = Builder() @JvmStatic fun fromEnv(): ClientOptions = builder().fromEnv().build() @@ -44,12 +69,14 @@ private constructor( class Builder internal constructor() { private var httpClient: HttpClient? = null + private var checkJacksonVersionCompatibility: Boolean = true private var jsonMapper: JsonMapper = jsonMapper() private var clock: Clock = Clock.systemUTC() private var baseUrl: String = PRODUCTION_URL private var headers: Headers.Builder = Headers.builder() private var queryParams: QueryParams.Builder = QueryParams.builder() private var responseValidation: Boolean = false + private var timeout: Timeout = Timeout.default() private var maxRetries: Int = 2 private var accessToken: String? = null private var clientId: String? = null @@ -59,12 +86,14 @@ private constructor( @JvmSynthetic internal fun from(clientOptions: ClientOptions) = apply { httpClient = clientOptions.originalHttpClient + checkJacksonVersionCompatibility = clientOptions.checkJacksonVersionCompatibility jsonMapper = clientOptions.jsonMapper clock = clientOptions.clock baseUrl = clientOptions.baseUrl headers = clientOptions.headers.toBuilder() queryParams = clientOptions.queryParams.toBuilder() responseValidation = clientOptions.responseValidation + timeout = clientOptions.timeout maxRetries = clientOptions.maxRetries accessToken = clientOptions.accessToken clientId = clientOptions.clientId @@ -74,6 +103,10 @@ private constructor( fun httpClient(httpClient: HttpClient) = apply { this.httpClient = httpClient } + fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { + this.checkJacksonVersionCompatibility = checkJacksonVersionCompatibility + } + fun jsonMapper(jsonMapper: JsonMapper) = apply { this.jsonMapper = jsonMapper } fun clock(clock: Clock) = apply { this.clock = clock } @@ -84,24 +117,30 @@ private constructor( this.responseValidation = responseValidation } + fun timeout(timeout: Timeout) = apply { this.timeout = timeout } + fun maxRetries(maxRetries: Int) = apply { this.maxRetries = maxRetries } fun accessToken(accessToken: String?) = apply { this.accessToken = accessToken } - fun accessToken(accessToken: Optional) = accessToken(accessToken.orElse(null)) + /** Alias for calling [Builder.accessToken] with `accessToken.orElse(null)`. */ + fun accessToken(accessToken: Optional) = accessToken(accessToken.getOrNull()) fun clientId(clientId: String?) = apply { this.clientId = clientId } - fun clientId(clientId: Optional) = clientId(clientId.orElse(null)) + /** Alias for calling [Builder.clientId] with `clientId.orElse(null)`. */ + fun clientId(clientId: Optional) = clientId(clientId.getOrNull()) fun clientSecret(clientSecret: String?) = apply { this.clientSecret = clientSecret } - fun clientSecret(clientSecret: Optional) = clientSecret(clientSecret.orElse(null)) + /** Alias for calling [Builder.clientSecret] with `clientSecret.orElse(null)`. */ + fun clientSecret(clientSecret: Optional) = clientSecret(clientSecret.getOrNull()) fun webhookSecret(webhookSecret: String?) = apply { this.webhookSecret = webhookSecret } + /** Alias for calling [Builder.webhookSecret] with `webhookSecret.orElse(null)`. */ fun webhookSecret(webhookSecret: Optional) = - webhookSecret(webhookSecret.orElse(null)) + webhookSecret(webhookSecret.getOrNull()) fun headers(headers: Headers) = apply { this.headers.clear() @@ -189,6 +228,18 @@ private constructor( System.getenv("FINCH_WEBHOOK_SECRET")?.let { webhookSecret(it) } } + /** + * Returns an immutable instance of [ClientOptions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .httpClient() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): ClientOptions { val httpClient = checkRequired("httpClient", httpClient) @@ -229,12 +280,14 @@ private constructor( .maxRetries(maxRetries) .build() ), + checkJacksonVersionCompatibility, jsonMapper, clock, baseUrl, headers.build(), queryParams.build(), responseValidation, + timeout, maxRetries, accessToken, clientId, diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/HttpRequestBodies.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/HttpRequestBodies.kt deleted file mode 100644 index 4d3d1862..00000000 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/HttpRequestBodies.kt +++ /dev/null @@ -1,108 +0,0 @@ -@file:JvmName("HttpRequestBodies") - -package com.tryfinch.api.core - -import com.fasterxml.jackson.databind.json.JsonMapper -import com.tryfinch.api.core.http.HttpRequestBody -import com.tryfinch.api.errors.FinchException -import java.io.ByteArrayOutputStream -import java.io.OutputStream -import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder - -@JvmSynthetic -internal inline fun json(jsonMapper: JsonMapper, value: T): HttpRequestBody { - return object : HttpRequestBody { - private var cachedBytes: ByteArray? = null - - private fun serialize(): ByteArray { - if (cachedBytes != null) return cachedBytes!! - - val buffer = ByteArrayOutputStream() - try { - jsonMapper.writeValue(buffer, value) - cachedBytes = buffer.toByteArray() - return cachedBytes!! - } catch (e: Exception) { - throw FinchException("Error writing request", e) - } - } - - override fun writeTo(outputStream: OutputStream) { - outputStream.write(serialize()) - } - - override fun contentType(): String = "application/json" - - override fun contentLength(): Long { - return serialize().size.toLong() - } - - override fun repeatable(): Boolean = true - - override fun close() {} - } -} - -@JvmSynthetic -internal fun multipartFormData( - jsonMapper: JsonMapper, - parts: Array?>, -): HttpRequestBody { - val builder = MultipartEntityBuilder.create() - parts.forEach { part -> - if (part?.value != null) { - when (part.value) { - is JsonValue -> { - val buffer = ByteArrayOutputStream() - try { - jsonMapper.writeValue(buffer, part.value) - } catch (e: Exception) { - throw FinchException("Error serializing value to json", e) - } - builder.addBinaryBody( - part.name, - buffer.toByteArray(), - part.contentType, - part.filename, - ) - } - is Boolean -> - builder.addTextBody( - part.name, - if (part.value) "true" else "false", - part.contentType, - ) - is Int -> builder.addTextBody(part.name, part.value.toString(), part.contentType) - is Long -> builder.addTextBody(part.name, part.value.toString(), part.contentType) - is Double -> builder.addTextBody(part.name, part.value.toString(), part.contentType) - is ByteArray -> - builder.addBinaryBody(part.name, part.value, part.contentType, part.filename) - is String -> builder.addTextBody(part.name, part.value, part.contentType) - is Enum -> builder.addTextBody(part.name, part.value.toString(), part.contentType) - else -> - throw IllegalArgumentException( - "Unsupported content type: ${part.value::class.java.simpleName}" - ) - } - } - } - val entity = builder.build() - - return object : HttpRequestBody { - override fun writeTo(outputStream: OutputStream) { - try { - return entity.writeTo(outputStream) - } catch (e: Exception) { - throw FinchException("Error writing request", e) - } - } - - override fun contentType(): String = entity.contentType - - override fun contentLength(): Long = -1 - - override fun repeatable(): Boolean = entity.isRepeatable - - override fun close() = entity.close() - } -} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/ObjectMappers.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/ObjectMappers.kt index 90d2ce0d..67e2acb4 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/ObjectMappers.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/ObjectMappers.kt @@ -3,23 +3,165 @@ package com.tryfinch.api.core import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.JsonParseException +import com.fasterxml.jackson.core.JsonParser +import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.DeserializationFeature +import com.fasterxml.jackson.databind.MapperFeature import com.fasterxml.jackson.databind.SerializationFeature -import com.fasterxml.jackson.databind.cfg.CoercionAction.Fail -import com.fasterxml.jackson.databind.cfg.CoercionInputShape.Integer +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.cfg.CoercionAction +import com.fasterxml.jackson.databind.cfg.CoercionInputShape +import com.fasterxml.jackson.databind.deser.std.StdDeserializer import com.fasterxml.jackson.databind.json.JsonMapper +import com.fasterxml.jackson.databind.module.SimpleModule +import com.fasterxml.jackson.databind.type.LogicalType import com.fasterxml.jackson.datatype.jdk8.Jdk8Module import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule -import com.fasterxml.jackson.module.kotlin.jacksonMapperBuilder +import com.fasterxml.jackson.module.kotlin.kotlinModule +import java.io.InputStream +import java.time.DateTimeException +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoField fun jsonMapper(): JsonMapper = - jacksonMapperBuilder() + JsonMapper.builder() + .addModule(kotlinModule()) .addModule(Jdk8Module()) .addModule(JavaTimeModule()) + .addModule( + SimpleModule() + .addSerializer(InputStreamSerializer) + .addDeserializer(LocalDateTime::class.java, LenientLocalDateTimeDeserializer()) + ) + .withCoercionConfig(LogicalType.Boolean) { + it.setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Integer) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Float) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Textual) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Array) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Collection) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.Map) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Object, CoercionAction.Fail) + } + .withCoercionConfig(LogicalType.POJO) { + it.setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.String, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Array, CoercionAction.Fail) + } .serializationInclusion(JsonInclude.Include.NON_ABSENT) .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) .disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .disable(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) - .withCoercionConfig(String::class.java) { it.setCoercion(Integer, Fail) } + .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) + .disable(MapperFeature.AUTO_DETECT_CREATORS) + .disable(MapperFeature.AUTO_DETECT_FIELDS) + .disable(MapperFeature.AUTO_DETECT_GETTERS) + .disable(MapperFeature.AUTO_DETECT_IS_GETTERS) + .disable(MapperFeature.AUTO_DETECT_SETTERS) .build() + +/** A serializer that serializes [InputStream] to bytes. */ +private object InputStreamSerializer : BaseSerializer(InputStream::class) { + + private fun readResolve(): Any = InputStreamSerializer + + override fun serialize( + value: InputStream?, + gen: JsonGenerator?, + serializers: SerializerProvider?, + ) { + if (value == null) { + gen?.writeNull() + } else { + value.use { gen?.writeBinary(it.readBytes()) } + } + } +} + +/** + * A deserializer that can deserialize [LocalDateTime] from datetimes, dates, and zoned datetimes. + */ +private class LenientLocalDateTimeDeserializer : + StdDeserializer(LocalDateTime::class.java) { + + companion object { + + private val DATE_TIME_FORMATTERS = + listOf( + DateTimeFormatter.ISO_LOCAL_DATE_TIME, + DateTimeFormatter.ISO_LOCAL_DATE, + DateTimeFormatter.ISO_ZONED_DATE_TIME, + ) + } + + override fun logicalType(): LogicalType = LogicalType.DateTime + + override fun deserialize(p: JsonParser, context: DeserializationContext?): LocalDateTime { + val exceptions = mutableListOf() + + for (formatter in DATE_TIME_FORMATTERS) { + try { + val temporal = formatter.parse(p.text) + + return when { + !temporal.isSupported(ChronoField.HOUR_OF_DAY) -> + LocalDate.from(temporal).atStartOfDay() + !temporal.isSupported(ChronoField.OFFSET_SECONDS) -> + LocalDateTime.from(temporal) + else -> ZonedDateTime.from(temporal).toLocalDateTime() + } + } catch (e: DateTimeException) { + exceptions.add(e) + } + } + + throw JsonParseException(p, "Cannot parse `LocalDateTime` from value: ${p.text}").apply { + exceptions.forEach { addSuppressed(it) } + } + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/RequestOptions.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/RequestOptions.kt index cee1a369..89fdd644 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/RequestOptions.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/RequestOptions.kt @@ -2,13 +2,7 @@ package com.tryfinch.api.core import java.time.Duration -class RequestOptions private constructor(val responseValidation: Boolean?, val timeout: Duration?) { - fun applyDefaults(options: RequestOptions): RequestOptions { - return RequestOptions( - responseValidation = this.responseValidation ?: options.responseValidation, - timeout = this.timeout ?: options.timeout, - ) - } +class RequestOptions private constructor(val responseValidation: Boolean?, val timeout: Timeout?) { companion object { @@ -16,22 +10,37 @@ class RequestOptions private constructor(val responseValidation: Boolean?, val t @JvmStatic fun none() = NONE + @JvmSynthetic + internal fun from(clientOptions: ClientOptions): RequestOptions = + builder() + .responseValidation(clientOptions.responseValidation) + .timeout(clientOptions.timeout) + .build() + @JvmStatic fun builder() = Builder() } + fun applyDefaults(options: RequestOptions): RequestOptions = + RequestOptions( + responseValidation = responseValidation ?: options.responseValidation, + timeout = + if (options.timeout != null && timeout != null) timeout.assign(options.timeout) + else timeout ?: options.timeout, + ) + class Builder internal constructor() { private var responseValidation: Boolean? = null - private var timeout: Duration? = null + private var timeout: Timeout? = null fun responseValidation(responseValidation: Boolean) = apply { this.responseValidation = responseValidation } - fun timeout(timeout: Duration) = apply { this.timeout = timeout } + fun timeout(timeout: Timeout) = apply { this.timeout = timeout } - fun build(): RequestOptions { - return RequestOptions(responseValidation, timeout) - } + fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) + + fun build(): RequestOptions = RequestOptions(responseValidation, timeout) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Timeout.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Timeout.kt new file mode 100644 index 00000000..eb2f4b95 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Timeout.kt @@ -0,0 +1,167 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.core + +import java.time.Duration +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** A class containing timeouts for various processing phases of a request. */ +class Timeout +private constructor( + private val connect: Duration?, + private val read: Duration?, + private val write: Duration?, + private val request: Duration?, +) { + + /** + * The maximum time allowed to establish a connection with a host. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `Duration.ofMinutes(1)`. + */ + fun connect(): Duration = connect ?: Duration.ofMinutes(1) + + /** + * The maximum time allowed between two data packets when waiting for the server’s response. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `request()`. + */ + fun read(): Duration = read ?: request() + + /** + * The maximum time allowed between two data packets when sending the request to the server. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `request()`. + */ + fun write(): Duration = write ?: request() + + /** + * The maximum time allowed for a complete HTTP call, not including retries. + * + * This includes resolving DNS, connecting, writing the request body, server processing, as well + * as reading the response body. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `Duration.ofMinutes(1)`. + */ + fun request(): Duration = request ?: Duration.ofMinutes(1) + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun default() = builder().build() + + /** Returns a mutable builder for constructing an instance of [Timeout]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Timeout]. */ + class Builder internal constructor() { + + private var connect: Duration? = null + private var read: Duration? = null + private var write: Duration? = null + private var request: Duration? = null + + @JvmSynthetic + internal fun from(timeout: Timeout) = apply { + connect = timeout.connect + read = timeout.read + write = timeout.write + request = timeout.request + } + + /** + * The maximum time allowed to establish a connection with a host. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `Duration.ofMinutes(1)`. + */ + fun connect(connect: Duration?) = apply { this.connect = connect } + + /** Alias for calling [Builder.connect] with `connect.orElse(null)`. */ + fun connect(connect: Optional) = connect(connect.getOrNull()) + + /** + * The maximum time allowed between two data packets when waiting for the server’s response. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `request()`. + */ + fun read(read: Duration?) = apply { this.read = read } + + /** Alias for calling [Builder.read] with `read.orElse(null)`. */ + fun read(read: Optional) = read(read.getOrNull()) + + /** + * The maximum time allowed between two data packets when sending the request to the server. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `request()`. + */ + fun write(write: Duration?) = apply { this.write = write } + + /** Alias for calling [Builder.write] with `write.orElse(null)`. */ + fun write(write: Optional) = write(write.getOrNull()) + + /** + * The maximum time allowed for a complete HTTP call, not including retries. + * + * This includes resolving DNS, connecting, writing the request body, server processing, as + * well as reading the response body. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `Duration.ofMinutes(1)`. + */ + fun request(request: Duration?) = apply { this.request = request } + + /** Alias for calling [Builder.request] with `request.orElse(null)`. */ + fun request(request: Optional) = request(request.getOrNull()) + + /** + * Returns an immutable instance of [Timeout]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Timeout = Timeout(connect, read, write, request) + } + + @JvmSynthetic + internal fun assign(target: Timeout): Timeout = + target + .toBuilder() + .apply { + connect?.let(this::connect) + read?.let(this::read) + write?.let(this::write) + request?.let(this::request) + } + .build() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Timeout && connect == other.connect && read == other.read && write == other.write && request == other.request /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(connect, read, write, request) /* spotless:on */ + + override fun toString() = + "Timeout{connect=$connect, read=$read, write=$write, request=$request}" +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Utils.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Utils.kt index 979a3580..3acb9ed3 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Utils.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Utils.kt @@ -26,6 +26,34 @@ internal fun , V> SortedMap.toImmutable(): SortedMap> Sequence.allMaxBy(selector: (T) -> R): List { + var maxValue: R? = null + val maxElements = mutableListOf() + + val iterator = iterator() + while (iterator.hasNext()) { + val element = iterator.next() + val value = selector(element) + if (maxValue == null || value > maxValue) { + maxValue = value + maxElements.clear() + maxElements.add(element) + } else if (value == maxValue) { + maxElements.add(element) + } + } + + return maxElements +} + /** * Returns whether [this] is equal to [other]. * diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Values.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Values.kt index 95574500..82a56e0e 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Values.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/Values.kt @@ -1,8 +1,6 @@ package com.tryfinch.api.core import com.fasterxml.jackson.annotation.JacksonAnnotationsInside -import com.fasterxml.jackson.annotation.JsonAutoDetect -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.core.JsonGenerator @@ -27,35 +25,55 @@ import com.fasterxml.jackson.databind.node.JsonNodeType.POJO import com.fasterxml.jackson.databind.node.JsonNodeType.STRING import com.fasterxml.jackson.databind.ser.std.NullSerializer import com.tryfinch.api.errors.FinchInvalidDataException -import java.nio.charset.Charset +import java.io.InputStream import java.util.Objects import java.util.Optional -import org.apache.hc.core5.http.ContentType +/** + * A class representing a serializable JSON field. + * + * It can either be a [KnownValue] value of type [T], matching the type the SDK expects, or an + * arbitrary JSON value that bypasses the type system (via [JsonValue]). + */ @JsonDeserialize(using = JsonField.Deserializer::class) sealed class JsonField { + /** + * Returns whether this field is missing, which means it will be omitted from the serialized + * JSON entirely. + */ fun isMissing(): Boolean = this is JsonMissing + /** Whether this field is explicitly set to `null`. */ fun isNull(): Boolean = this is JsonNull - fun asKnown(): Optional = - when (this) { - is KnownValue -> Optional.of(value) - else -> Optional.empty() - } + /** + * Returns an [Optional] containing this field's "known" value, meaning it matches the type the + * SDK expects, or an empty [Optional] if this field contains an arbitrary [JsonValue]. + * + * This is the opposite of [asUnknown]. + */ + fun asKnown(): + Optional< + // Safe because `Optional` is effectively covariant, but Kotlin doesn't know that. + @UnsafeVariance + T + > = Optional.ofNullable((this as? KnownValue)?.value) /** - * If the "known" value (i.e. matching the type that the SDK expects) is returned by the API - * then this method will return an empty `Optional`, otherwise the returned `Optional` is given - * a `JsonValue`. + * Returns an [Optional] containing this field's arbitrary [JsonValue], meaning it mismatches + * the type the SDK expects, or an empty [Optional] if this field contains a "known" value. + * + * This is the opposite of [asKnown]. */ - fun asUnknown(): Optional = - when (this) { - is JsonValue -> Optional.of(this) - else -> Optional.empty() - } + fun asUnknown(): Optional = Optional.ofNullable(this as? JsonValue) + /** + * Returns an [Optional] containing this field's boolean value, or an empty [Optional] if it + * doesn't contain a boolean. + * + * This method checks for both a [KnownValue] containing a boolean and for [JsonBoolean]. + */ fun asBoolean(): Optional = when (this) { is JsonBoolean -> Optional.of(value) @@ -63,6 +81,12 @@ sealed class JsonField { else -> Optional.empty() } + /** + * Returns an [Optional] containing this field's numerical value, or an empty [Optional] if it + * doesn't contain a number. + * + * This method checks for both a [KnownValue] containing a number and for [JsonNumber]. + */ fun asNumber(): Optional = when (this) { is JsonNumber -> Optional.of(value) @@ -70,6 +94,12 @@ sealed class JsonField { else -> Optional.empty() } + /** + * Returns an [Optional] containing this field's string value, or an empty [Optional] if it + * doesn't contain a string. + * + * This method checks for both a [KnownValue] containing a string and for [JsonString]. + */ fun asString(): Optional = when (this) { is JsonString -> Optional.of(value) @@ -80,6 +110,12 @@ sealed class JsonField { fun asStringOrThrow(): String = asString().orElseThrow { FinchInvalidDataException("Value is not a string") } + /** + * Returns an [Optional] containing this field's list value, or an empty [Optional] if it + * doesn't contain a list. + * + * This method checks for both a [KnownValue] containing a list and for [JsonArray]. + */ fun asArray(): Optional> = when (this) { is JsonArray -> Optional.of(values) @@ -98,6 +134,12 @@ sealed class JsonField { else -> Optional.empty() } + /** + * Returns an [Optional] containing this field's map value, or an empty [Optional] if it doesn't + * contain a map. + * + * This method checks for both a [KnownValue] containing a map and for [JsonObject]. + */ fun asObject(): Optional> = when (this) { is JsonObject -> Optional.of(values) @@ -135,11 +177,17 @@ sealed class JsonField { } @JvmSynthetic - internal fun getNullable(name: String): T? = + internal fun getOptional( + name: String + ): Optional< + // Safe because `Optional` is effectively covariant, but Kotlin doesn't know that. + @UnsafeVariance + T + > = when (this) { - is KnownValue -> value - is JsonMissing -> null - is JsonNull -> null + is KnownValue -> Optional.of(value) + is JsonMissing, + is JsonNull -> Optional.empty() else -> throw FinchInvalidDataException("`$name` is invalid, received $this") } @@ -150,21 +198,33 @@ sealed class JsonField { is JsonValue -> this } - @JvmSynthetic fun accept(consume: (T) -> Unit) = asKnown().ifPresent(consume) + @JvmSynthetic internal fun accept(consume: (T) -> Unit) = asKnown().ifPresent(consume) + /** Returns the result of calling the [visitor] method corresponding to this field's state. */ fun accept(visitor: Visitor): R = when (this) { is KnownValue -> visitor.visitKnown(value) is JsonValue -> accept(visitor as JsonValue.Visitor) } + /** + * An interface that defines how to map each possible state of a `JsonField` to a value of + * type [R]. + */ interface Visitor : JsonValue.Visitor { + fun visitKnown(value: T): R = visitDefault() } companion object { + + /** Returns a [JsonField] containing the given "known" [value]. */ @JvmStatic fun of(value: T): JsonField = KnownValue.of(value) + /** + * Returns a [JsonField] containing the given "known" [value], or [JsonNull] if [value] is + * null. + */ @JvmStatic fun ofNullable(value: T?): JsonField = when (value) { @@ -179,6 +239,7 @@ sealed class JsonField { * annotation. */ class IsMissing { + override fun equals(other: Any?): Boolean = other is JsonMissing override fun hashCode(): Int = Objects.hash() @@ -200,6 +261,12 @@ sealed class JsonField { } } +/** + * A class representing an arbitrary JSON value. + * + * It is immutable and assignable to any [JsonField], regardless of its expected type (i.e. its + * generic type argument). + */ @JsonDeserialize(using = JsonValue.Deserializer::class) sealed class JsonValue : JsonField() { @@ -207,6 +274,7 @@ sealed class JsonValue : JsonField() { fun convert(type: Class): R? = JSON_MAPPER.convertValue(this, type) + /** Returns the result of calling the [visitor] method corresponding to this value's variant. */ fun accept(visitor: Visitor): R = when (this) { is JsonMissing -> visitor.visitMissing() @@ -218,7 +286,12 @@ sealed class JsonValue : JsonField() { is JsonObject -> visitor.visitObject(values) } + /** + * An interface that defines how to map each variant state of a [JsonValue] to a value of type + * [R]. + */ interface Visitor { + fun visitNull(): R = visitDefault() fun visitMissing(): R = visitDefault() @@ -233,15 +306,52 @@ sealed class JsonValue : JsonField() { fun visitObject(values: Map): R = visitDefault() - fun visitDefault(): R { - throw RuntimeException("Unexpected value") - } + /** + * The default implementation for unimplemented visitor methods. + * + * @throws IllegalArgumentException in the default implementation. + */ + fun visitDefault(): R = throw IllegalArgumentException("Unexpected value") } companion object { private val JSON_MAPPER = jsonMapper() + /** + * Converts the given [value] to a [JsonValue]. + * + * This method works best on primitive types, [List] values, [Map] values, and nested + * combinations of these. For example: + * ```java + * // Create primitive JSON values + * JsonValue nullValue = JsonValue.from(null); + * JsonValue booleanValue = JsonValue.from(true); + * JsonValue numberValue = JsonValue.from(42); + * JsonValue stringValue = JsonValue.from("Hello World!"); + * + * // Create a JSON array value equivalent to `["Hello", "World"]` + * JsonValue arrayValue = JsonValue.from(List.of("Hello", "World")); + * + * // Create a JSON object value equivalent to `{ "a": 1, "b": 2 }` + * JsonValue objectValue = JsonValue.from(Map.of( + * "a", 1, + * "b", 2 + * )); + * + * // Create an arbitrarily nested JSON equivalent to: + * // { + * // "a": [1, 2], + * // "b": [3, 4] + * // } + * JsonValue complexValue = JsonValue.from(Map.of( + * "a", List.of(1, 2), + * "b", List.of(3, 4) + * )); + * ``` + * + * @throws IllegalArgumentException if [value] is not JSON serializable. + */ @JvmStatic fun from(value: Any?): JsonValue = when (value) { @@ -250,6 +360,11 @@ sealed class JsonValue : JsonField() { else -> JSON_MAPPER.convertValue(value, JsonValue::class.java) } + /** + * Returns a [JsonValue] converted from the given Jackson [JsonNode]. + * + * @throws IllegalStateException for unsupported node types. + */ @JvmStatic fun fromJsonNode(node: JsonNode): JsonValue = when (node.nodeType) { @@ -271,12 +386,19 @@ sealed class JsonValue : JsonField() { } class Deserializer : BaseDeserializer(JsonValue::class) { + override fun ObjectCodec.deserialize(node: JsonNode): JsonValue = fromJsonNode(node) override fun getNullValue(context: DeserializationContext?): JsonValue = JsonNull.of() } } +/** + * A class representing a "known" JSON serializable value of type [T], matching the type the SDK + * expects. + * + * It is assignable to `JsonField`. + */ class KnownValue private constructor( @com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: T @@ -287,52 +409,67 @@ private constructor( return true } - return other is KnownValue<*> && value == other.value + return other is KnownValue<*> && value contentEquals other.value } - override fun hashCode() = value.hashCode() + override fun hashCode() = contentHash(value) - override fun toString() = value.toString() + override fun toString() = value.contentToString() companion object { + + /** Returns a [KnownValue] containing the given [value]. */ @JsonCreator @JvmStatic fun of(value: T) = KnownValue(value) } } +/** + * A [JsonValue] representing an omitted JSON field. + * + * An instance of this class will cause a JSON field to be omitted from the serialized JSON + * entirely. + */ @JsonSerialize(using = JsonMissing.Serializer::class) class JsonMissing : JsonValue() { override fun toString() = "" companion object { + private val INSTANCE: JsonMissing = JsonMissing() + /** Returns the singleton instance of [JsonMissing]. */ @JvmStatic fun of() = INSTANCE } class Serializer : BaseSerializer(JsonMissing::class) { + override fun serialize( value: JsonMissing, generator: JsonGenerator, provider: SerializerProvider, ) { - throw RuntimeException("JsonMissing cannot be serialized") + throw IllegalStateException("JsonMissing cannot be serialized") } } } +/** A [JsonValue] representing a JSON `null` value. */ @JsonSerialize(using = NullSerializer::class) class JsonNull : JsonValue() { override fun toString() = "null" companion object { + private val INSTANCE: JsonNull = JsonNull() + /** Returns the singleton instance of [JsonMissing]. */ @JsonCreator @JvmStatic fun of() = INSTANCE } } +/** A [JsonValue] representing a JSON boolean value. */ class JsonBoolean private constructor( @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: Boolean @@ -351,14 +488,18 @@ private constructor( override fun toString() = value.toString() companion object { + + /** Returns a [JsonBoolean] containing the given [value]. */ @JsonCreator @JvmStatic fun of(value: Boolean) = JsonBoolean(value) } } +/** A [JsonValue] representing a JSON number value. */ class JsonNumber private constructor( @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: Number ) : JsonValue() { + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -372,10 +513,13 @@ private constructor( override fun toString() = value.toString() companion object { + + /** Returns a [JsonNumber] containing the given [value]. */ @JsonCreator @JvmStatic fun of(value: Number) = JsonNumber(value) } } +/** A [JsonValue] representing a JSON string value. */ class JsonString private constructor( @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: String @@ -394,10 +538,13 @@ private constructor( override fun toString() = value companion object { + + /** Returns a [JsonString] containing the given [value]. */ @JsonCreator @JvmStatic fun of(value: String) = JsonString(value) } } +/** A [JsonValue] representing a JSON array value. */ class JsonArray private constructor( @get:com.fasterxml.jackson.annotation.JsonValue @@ -418,10 +565,13 @@ private constructor( override fun toString() = values.toString() companion object { + + /** Returns a [JsonArray] containing the given [values]. */ @JsonCreator @JvmStatic fun of(values: List) = JsonArray(values.toImmutable()) } } +/** A [JsonValue] representing a JSON object value. */ class JsonObject private constructor( @get:com.fasterxml.jackson.annotation.JsonValue @@ -442,35 +592,118 @@ private constructor( override fun toString() = values.toString() companion object { + + /** Returns a [JsonObject] containing the given [values]. */ @JsonCreator @JvmStatic fun of(values: Map) = JsonObject(values.toImmutable()) } } +/** A Jackson annotation for excluding fields set to [JsonMissing] from the serialized JSON. */ @JacksonAnnotationsInside @JsonInclude(JsonInclude.Include.CUSTOM, valueFilter = JsonField.IsMissing::class) annotation class ExcludeMissing -@JacksonAnnotationsInside -@JsonAutoDetect( - getterVisibility = Visibility.NONE, - isGetterVisibility = Visibility.NONE, - setterVisibility = Visibility.NONE, - creatorVisibility = Visibility.NONE, - fieldVisibility = Visibility.NONE, -) -annotation class NoAutoDetect - -class MultipartFormValue -internal constructor( - val name: String, - val value: T, - val contentType: ContentType, - val filename: String? = null, +/** A class representing a field in a `multipart/form-data` request. */ +class MultipartField +private constructor( + /** A [JsonField] value, which will be serialized to zero or more parts. */ + @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: JsonField, + /** A content type for the serialized parts. */ + @get:JvmName("contentType") val contentType: String, + private val filename: String?, ) { - private val hashCode: Int by lazy { contentHash(name, value, contentType, filename) } + companion object { + + /** + * Returns a [MultipartField] containing the given [value] as a [KnownValue]. + * + * [contentType] will be set to `application/octet-stream` if [value] is binary data, or + * `text/plain; charset=utf-8` otherwise. + */ + @JvmStatic fun of(value: T?) = builder().value(value).build() + + /** + * Returns a [MultipartField] containing the given [value]. + * + * [contentType] will be set to `application/octet-stream` if [value] is binary data, or + * `text/plain; charset=utf-8` otherwise. + */ + @JvmStatic fun of(value: JsonField) = builder().value(value).build() + + /** + * Returns a mutable builder for constructing an instance of [MultipartField]. + * + * The following fields are required: + * ```java + * .value() + * ``` + * + * If [contentType] is unset, then it will be set to `application/octet-stream` if [value] + * is binary data, or `text/plain; charset=utf-8` otherwise. + */ + @JvmStatic fun builder() = Builder() + } + + /** Returns the filename directive that will be included in the serialized field. */ + fun filename(): Optional = Optional.ofNullable(filename) + + @JvmSynthetic + internal fun map(transform: (T) -> R): MultipartField = + builder().value(value.map(transform)).contentType(contentType).filename(filename).build() + + /** A builder for [MultipartField]. */ + class Builder internal constructor() { + + private var value: JsonField? = null + private var contentType: String? = null + private var filename: String? = null + + fun value(value: JsonField) = apply { this.value = value } + + fun value(value: T?) = value(JsonField.ofNullable(value)) + + fun contentType(contentType: String) = apply { this.contentType = contentType } + + fun filename(filename: String?) = apply { this.filename = filename } + + /** Alias for calling [Builder.filename] with `filename.orElse(null)`. */ + fun filename(filename: Optional) = filename(filename.orElse(null)) + + /** + * Returns an immutable instance of [MultipartField]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .value() + * ``` + * + * If [contentType] is unset, then it will be set to `application/octet-stream` if [value] + * is binary data, or `text/plain; charset=utf-8` otherwise. + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): MultipartField { + val value = checkRequired("value", value) + return MultipartField( + value, + contentType + ?: if ( + value is KnownValue && + (value.value is InputStream || value.value is ByteArray) + ) + "application/octet-stream" + else "text/plain; charset=utf-8", + filename, + ) + } + } + + private val hashCode: Int by lazy { contentHash(value, contentType, filename) } override fun hashCode(): Int = hashCode @@ -479,63 +712,12 @@ internal constructor( return true } - return other is MultipartFormValue<*> && - name == other.name && - value contentEquals other.value && + return other is MultipartField<*> && + value == other.value && contentType == other.contentType && filename == other.filename } override fun toString(): String = - "MultipartFormValue{name=$name, contentType=$contentType, filename=$filename, value=${valueToString()}}" - - private fun valueToString(): String = - when (value) { - is ByteArray -> "ByteArray of size ${value.size}" - else -> value.toString() - } - - companion object { - internal fun fromString( - name: String, - value: String, - contentType: ContentType, - ): MultipartFormValue = MultipartFormValue(name, value, contentType) - - internal fun fromBoolean( - name: String, - value: Boolean, - contentType: ContentType, - ): MultipartFormValue = MultipartFormValue(name, value, contentType) - - internal fun fromLong( - name: String, - value: Long, - contentType: ContentType, - ): MultipartFormValue = MultipartFormValue(name, value, contentType) - - internal fun fromDouble( - name: String, - value: Double, - contentType: ContentType, - ): MultipartFormValue = MultipartFormValue(name, value, contentType) - - internal fun fromEnum( - name: String, - value: T, - contentType: ContentType, - ): MultipartFormValue = MultipartFormValue(name, value, contentType) - - internal fun fromByteArray( - name: String, - value: ByteArray, - contentType: ContentType, - filename: String? = null, - ): MultipartFormValue = MultipartFormValue(name, value, contentType, filename) - } -} - -internal object ContentTypes { - val DefaultText = ContentType.create(ContentType.TEXT_PLAIN.mimeType, Charset.forName("UTF-8")) - val DefaultBinary = ContentType.DEFAULT_BINARY + "MultipartField{value=$value, contentType=$contentType, filename=$filename}" } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/handlers/ErrorHandler.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/handlers/ErrorHandler.kt index e583efa0..578e8a45 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/handlers/ErrorHandler.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/handlers/ErrorHandler.kt @@ -1,13 +1,15 @@ +// File generated from our OpenAPI spec by Stainless. + @file:JvmName("ErrorHandler") package com.tryfinch.api.core.handlers import com.fasterxml.jackson.databind.json.JsonMapper -import com.tryfinch.api.core.http.Headers +import com.tryfinch.api.core.JsonMissing +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.http.HttpResponse import com.tryfinch.api.core.http.HttpResponse.Handler import com.tryfinch.api.errors.BadRequestException -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.errors.InternalServerException import com.tryfinch.api.errors.NotFoundException import com.tryfinch.api.errors.PermissionDeniedException @@ -15,111 +17,68 @@ import com.tryfinch.api.errors.RateLimitException import com.tryfinch.api.errors.UnauthorizedException import com.tryfinch.api.errors.UnexpectedStatusCodeException import com.tryfinch.api.errors.UnprocessableEntityException -import java.io.ByteArrayInputStream -import java.io.InputStream @JvmSynthetic -internal fun errorHandler(jsonMapper: JsonMapper): Handler { - val handler = jsonHandler(jsonMapper) +internal fun errorHandler(jsonMapper: JsonMapper): Handler { + val handler = jsonHandler(jsonMapper) - return object : Handler { - override fun handle(response: HttpResponse): FinchError = + return object : Handler { + override fun handle(response: HttpResponse): JsonValue = try { handler.handle(response) } catch (e: Exception) { - FinchError.builder().build() + JsonMissing.of() } } } @JvmSynthetic -internal fun Handler.withErrorHandler(errorHandler: Handler): Handler = +internal fun Handler.withErrorHandler(errorHandler: Handler): Handler = object : Handler { - override fun handle(response: HttpResponse): T { + override fun handle(response: HttpResponse): T = when (val statusCode = response.statusCode()) { - in 200..299 -> { - return this@withErrorHandler.handle(response) - } - 400 -> { - val buffered = response.buffered() - throw BadRequestException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 401 -> { - val buffered = response.buffered() - throw UnauthorizedException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 403 -> { - val buffered = response.buffered() - throw PermissionDeniedException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 404 -> { - val buffered = response.buffered() - throw NotFoundException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 422 -> { - val buffered = response.buffered() - throw UnprocessableEntityException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - 429 -> { - val buffered = response.buffered() - throw RateLimitException( - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - in 500..599 -> { - val buffered = response.buffered() - throw InternalServerException( - statusCode, - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } - else -> { - val buffered = response.buffered() - throw UnexpectedStatusCodeException( - statusCode, - buffered.headers(), - stringHandler().handle(buffered), - errorHandler.handle(buffered), - ) - } + in 200..299 -> this@withErrorHandler.handle(response) + 400 -> + throw BadRequestException.builder() + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + 401 -> + throw UnauthorizedException.builder() + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + 403 -> + throw PermissionDeniedException.builder() + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + 404 -> + throw NotFoundException.builder() + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + 422 -> + throw UnprocessableEntityException.builder() + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + 429 -> + throw RateLimitException.builder() + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + in 500..599 -> + throw InternalServerException.builder() + .statusCode(statusCode) + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() + else -> + throw UnexpectedStatusCodeException.builder() + .statusCode(statusCode) + .headers(response.headers()) + .body(errorHandler.handle(response)) + .build() } - } - } - -private fun HttpResponse.buffered(): HttpResponse { - val body = body().readBytes() - - return object : HttpResponse { - override fun statusCode(): Int = this@buffered.statusCode() - - override fun headers(): Headers = this@buffered.headers() - - override fun body(): InputStream = ByteArrayInputStream(body) - - override fun close() = this@buffered.close() } -} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/handlers/JsonHandler.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/handlers/JsonHandler.kt index 825b04fb..f083697d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/handlers/JsonHandler.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/handlers/JsonHandler.kt @@ -6,16 +6,15 @@ import com.fasterxml.jackson.databind.json.JsonMapper import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import com.tryfinch.api.core.http.HttpResponse import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.errors.FinchException +import com.tryfinch.api.errors.FinchInvalidDataException @JvmSynthetic internal inline fun jsonHandler(jsonMapper: JsonMapper): Handler = object : Handler { - override fun handle(response: HttpResponse): T { + override fun handle(response: HttpResponse): T = try { - return jsonMapper.readValue(response.body(), jacksonTypeRef()) + jsonMapper.readValue(response.body(), jacksonTypeRef()) } catch (e: Exception) { - throw FinchException("Error reading response", e) + throw FinchInvalidDataException("Error reading response", e) } - } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpClient.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpClient.kt index 293114df..c92fc53a 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpClient.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpClient.kt @@ -1,5 +1,3 @@ -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.core.http import com.tryfinch.api.core.RequestOptions @@ -8,18 +6,21 @@ import java.util.concurrent.CompletableFuture interface HttpClient : AutoCloseable { - @JvmOverloads fun execute( request: HttpRequest, requestOptions: RequestOptions = RequestOptions.none(), ): HttpResponse - @JvmOverloads + fun execute(request: HttpRequest): HttpResponse = execute(request, RequestOptions.none()) + fun executeAsync( request: HttpRequest, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + fun executeAsync(request: HttpRequest): CompletableFuture = + executeAsync(request, RequestOptions.none()) + /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ override fun close() } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpRequestBodies.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpRequestBodies.kt new file mode 100644 index 00000000..9aee7f83 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpRequestBodies.kt @@ -0,0 +1,106 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:JvmName("HttpRequestBodies") + +package com.tryfinch.api.core.http + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.json.JsonMapper +import com.fasterxml.jackson.databind.node.JsonNodeType +import com.tryfinch.api.core.MultipartField +import com.tryfinch.api.errors.FinchInvalidDataException +import java.io.InputStream +import java.io.OutputStream +import kotlin.jvm.optionals.getOrNull +import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder +import org.apache.hc.core5.http.ContentType +import org.apache.hc.core5.http.HttpEntity + +@JvmSynthetic +internal inline fun json(jsonMapper: JsonMapper, value: T): HttpRequestBody = + object : HttpRequestBody { + private val bytes: ByteArray by lazy { jsonMapper.writeValueAsBytes(value) } + + override fun writeTo(outputStream: OutputStream) = outputStream.write(bytes) + + override fun contentType(): String = "application/json" + + override fun contentLength(): Long = bytes.size.toLong() + + override fun repeatable(): Boolean = true + + override fun close() {} + } + +@JvmSynthetic +internal fun multipartFormData( + jsonMapper: JsonMapper, + fields: Map>, +): HttpRequestBody = + object : HttpRequestBody { + private val entity: HttpEntity by lazy { + MultipartEntityBuilder.create() + .apply { + fields.forEach { (name, field) -> + val knownValue = field.value.asKnown().getOrNull() + val parts = + if (knownValue is InputStream) { + // Read directly from the `InputStream` instead of reading it all + // into memory due to the `jsonMapper` serialization below. + sequenceOf(name to knownValue) + } else { + val node = jsonMapper.valueToTree(field.value) + serializePart(name, node) + } + + parts.forEach { (name, bytes) -> + addBinaryBody( + name, + bytes, + ContentType.parseLenient(field.contentType), + field.filename().getOrNull(), + ) + } + } + } + .build() + } + + private fun serializePart( + name: String, + node: JsonNode, + ): Sequence> = + when (node.nodeType) { + JsonNodeType.MISSING, + JsonNodeType.NULL -> emptySequence() + JsonNodeType.BINARY -> sequenceOf(name to node.binaryValue().inputStream()) + JsonNodeType.STRING -> sequenceOf(name to node.textValue().inputStream()) + JsonNodeType.BOOLEAN -> + sequenceOf(name to node.booleanValue().toString().inputStream()) + JsonNodeType.NUMBER -> + sequenceOf(name to node.numberValue().toString().inputStream()) + JsonNodeType.ARRAY -> + node.elements().asSequence().flatMap { element -> + serializePart("$name[]", element) + } + JsonNodeType.OBJECT -> + node.fields().asSequence().flatMap { (key, value) -> + serializePart("$name[$key]", value) + } + JsonNodeType.POJO, + null -> + throw FinchInvalidDataException("Unexpected JsonNode type: ${node.nodeType}") + } + + private fun String.inputStream(): InputStream = toByteArray().inputStream() + + override fun writeTo(outputStream: OutputStream) = entity.writeTo(outputStream) + + override fun contentType(): String = entity.contentType + + override fun contentLength(): Long = entity.contentLength + + override fun repeatable(): Boolean = entity.isRepeatable + + override fun close() = entity.close() + } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpResponse.kt index ad9844e8..055286f6 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpResponse.kt @@ -1,7 +1,8 @@ +// File generated from our OpenAPI spec by Stainless. + package com.tryfinch.api.core.http import java.io.InputStream -import java.lang.AutoCloseable interface HttpResponse : AutoCloseable { diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpResponseFor.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpResponseFor.kt new file mode 100644 index 00000000..94b019b6 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/HttpResponseFor.kt @@ -0,0 +1,25 @@ +package com.tryfinch.api.core.http + +import java.io.InputStream + +interface HttpResponseFor : HttpResponse { + + fun parse(): T +} + +@JvmSynthetic +internal fun HttpResponse.parseable(parse: () -> T): HttpResponseFor = + object : HttpResponseFor { + + private val parsed: T by lazy { parse() } + + override fun parse(): T = parsed + + override fun statusCode(): Int = this@parseable.statusCode() + + override fun headers(): Headers = this@parseable.headers() + + override fun body(): InputStream = this@parseable.body() + + override fun close() = this@parseable.close() + } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/QueryParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/QueryParams.kt index e35ea929..9d2ff7c5 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/QueryParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/core/http/QueryParams.kt @@ -1,3 +1,5 @@ +// File generated from our OpenAPI spec by Stainless. + package com.tryfinch.api.core.http import com.tryfinch.api.core.toImmutable diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/BadRequestException.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/BadRequestException.kt index 1375ba00..6b42dcad 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/BadRequestException.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/BadRequestException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.tryfinch.api.errors +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class BadRequestException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + FinchServiceException("400: $body", cause) { + + override fun statusCode(): Int = 400 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [BadRequestException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BadRequestException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(badRequestException: BadRequestException) = apply { + headers = badRequestException.headers + body = badRequestException.body + cause = badRequestException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class BadRequestException(headers: Headers, body: String, error: FinchError) : - FinchServiceException(400, headers, body, error) + /** + * Returns an immutable instance of [BadRequestException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): BadRequestException = + BadRequestException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/FinchError.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/FinchError.kt deleted file mode 100644 index db1b299f..00000000 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/FinchError.kt +++ /dev/null @@ -1,76 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.tryfinch.api.errors - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.tryfinch.api.core.ExcludeMissing -import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable -import java.util.Objects - -@NoAutoDetect -class FinchError -@JsonCreator -private constructor( - @JsonAnyGetter - @ExcludeMissing - @JsonAnySetter - @get:JvmName("additionalProperties") - val additionalProperties: Map = immutableEmptyMap() -) { - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [FinchError]. */ - class Builder internal constructor() { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(finchError: FinchError) = apply { - additionalProperties = finchError.additionalProperties.toMutableMap() - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): FinchError = FinchError(additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is FinchError && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalProperties) /* spotless:on */ - - override fun toString() = "FinchError{additionalProperties=$additionalProperties}" -} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/FinchServiceException.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/FinchServiceException.kt index 9fa5ecc4..252842ed 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/FinchServiceException.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/FinchServiceException.kt @@ -1,23 +1,16 @@ +// File generated from our OpenAPI spec by Stainless. + package com.tryfinch.api.errors +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.http.Headers abstract class FinchServiceException -@JvmOverloads -constructor( - private val statusCode: Int, - private val headers: Headers, - private val body: String, - private val error: FinchError, - message: String = "$statusCode: $error", - cause: Throwable? = null, -) : FinchException(message, cause) { - - fun statusCode(): Int = statusCode +protected constructor(message: String, cause: Throwable? = null) : FinchException(message, cause) { - fun headers(): Headers = headers + abstract fun statusCode(): Int - fun body(): String = body + abstract fun headers(): Headers - fun error(): FinchError = error + abstract fun body(): JsonValue } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/InternalServerException.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/InternalServerException.kt index 8701e4a7..0e432de3 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/InternalServerException.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/InternalServerException.kt @@ -1,6 +1,91 @@ +// File generated from our OpenAPI spec by Stainless. + package com.tryfinch.api.errors +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class InternalServerException +private constructor( + private val statusCode: Int, + private val headers: Headers, + private val body: JsonValue, + cause: Throwable?, +) : FinchServiceException("$statusCode: $body", cause) { + + override fun statusCode(): Int = statusCode + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [InternalServerException]. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InternalServerException]. */ + class Builder internal constructor() { + + private var statusCode: Int? = null + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(internalServerException: InternalServerException) = apply { + statusCode = internalServerException.statusCode + headers = internalServerException.headers + body = internalServerException.body + cause = internalServerException.cause + } + + fun statusCode(statusCode: Int) = apply { this.statusCode = statusCode } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class InternalServerException(statusCode: Int, headers: Headers, body: String, error: FinchError) : - FinchServiceException(statusCode, headers, body, error) + /** + * Returns an immutable instance of [InternalServerException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InternalServerException = + InternalServerException( + checkRequired("statusCode", statusCode), + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/NotFoundException.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/NotFoundException.kt index 370a60c4..78219c0c 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/NotFoundException.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/NotFoundException.kt @@ -1,6 +1,76 @@ +// File generated from our OpenAPI spec by Stainless. + package com.tryfinch.api.errors +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class NotFoundException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + FinchServiceException("404: $body", cause) { + + override fun statusCode(): Int = 404 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [NotFoundException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [NotFoundException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(notFoundException: NotFoundException) = apply { + headers = notFoundException.headers + body = notFoundException.body + cause = notFoundException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class NotFoundException(headers: Headers, body: String, error: FinchError) : - FinchServiceException(404, headers, body, error) + /** + * Returns an immutable instance of [NotFoundException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): NotFoundException = + NotFoundException(checkRequired("headers", headers), checkRequired("body", body), cause) + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/PermissionDeniedException.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/PermissionDeniedException.kt index 36058d72..b43c0875 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/PermissionDeniedException.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/PermissionDeniedException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.tryfinch.api.errors +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class PermissionDeniedException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + FinchServiceException("403: $body", cause) { + + override fun statusCode(): Int = 403 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [PermissionDeniedException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PermissionDeniedException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(permissionDeniedException: PermissionDeniedException) = apply { + headers = permissionDeniedException.headers + body = permissionDeniedException.body + cause = permissionDeniedException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class PermissionDeniedException(headers: Headers, body: String, error: FinchError) : - FinchServiceException(403, headers, body, error) + /** + * Returns an immutable instance of [PermissionDeniedException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): PermissionDeniedException = + PermissionDeniedException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/RateLimitException.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/RateLimitException.kt index f14024da..02907cfc 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/RateLimitException.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/RateLimitException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.tryfinch.api.errors +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class RateLimitException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + FinchServiceException("429: $body", cause) { + + override fun statusCode(): Int = 429 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RateLimitException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RateLimitException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(rateLimitException: RateLimitException) = apply { + headers = rateLimitException.headers + body = rateLimitException.body + cause = rateLimitException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class RateLimitException(headers: Headers, body: String, error: FinchError) : - FinchServiceException(429, headers, body, error) + /** + * Returns an immutable instance of [RateLimitException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RateLimitException = + RateLimitException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnauthorizedException.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnauthorizedException.kt index a060f3d4..91143b9d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnauthorizedException.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnauthorizedException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.tryfinch.api.errors +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class UnauthorizedException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + FinchServiceException("401: $body", cause) { + + override fun statusCode(): Int = 401 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UnauthorizedException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnauthorizedException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(unauthorizedException: UnauthorizedException) = apply { + headers = unauthorizedException.headers + body = unauthorizedException.body + cause = unauthorizedException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class UnauthorizedException(headers: Headers, body: String, error: FinchError) : - FinchServiceException(401, headers, body, error) + /** + * Returns an immutable instance of [UnauthorizedException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UnauthorizedException = + UnauthorizedException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnexpectedStatusCodeException.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnexpectedStatusCodeException.kt index 46de2a14..5d89680b 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnexpectedStatusCodeException.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnexpectedStatusCodeException.kt @@ -1,10 +1,92 @@ +// File generated from our OpenAPI spec by Stainless. + package com.tryfinch.api.errors +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class UnexpectedStatusCodeException +private constructor( + private val statusCode: Int, + private val headers: Headers, + private val body: JsonValue, + cause: Throwable?, +) : FinchServiceException("$statusCode: $body", cause) { + + override fun statusCode(): Int = statusCode + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [UnexpectedStatusCodeException]. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnexpectedStatusCodeException]. */ + class Builder internal constructor() { + + private var statusCode: Int? = null + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(unexpectedStatusCodeException: UnexpectedStatusCodeException) = apply { + statusCode = unexpectedStatusCodeException.statusCode + headers = unexpectedStatusCodeException.headers + body = unexpectedStatusCodeException.body + cause = unexpectedStatusCodeException.cause + } + + fun statusCode(statusCode: Int) = apply { this.statusCode = statusCode } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class UnexpectedStatusCodeException( - statusCode: Int, - headers: Headers, - body: String, - error: FinchError, -) : FinchServiceException(statusCode, headers, body, error) + /** + * Returns an immutable instance of [UnexpectedStatusCodeException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UnexpectedStatusCodeException = + UnexpectedStatusCodeException( + checkRequired("statusCode", statusCode), + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnprocessableEntityException.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnprocessableEntityException.kt index 6efe853c..c937818a 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnprocessableEntityException.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/errors/UnprocessableEntityException.kt @@ -1,6 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.tryfinch.api.errors +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class UnprocessableEntityException +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + FinchServiceException("422: $body", cause) { + + override fun statusCode(): Int = 422 + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UnprocessableEntityException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnprocessableEntityException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(unprocessableEntityException: UnprocessableEntityException) = apply { + headers = unprocessableEntityException.headers + body = unprocessableEntityException.body + cause = unprocessableEntityException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) -class UnprocessableEntityException(headers: Headers, body: String, error: FinchError) : - FinchServiceException(422, headers, body, error) + /** + * Returns an immutable instance of [UnprocessableEntityException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UnprocessableEntityException = + UnprocessableEntityException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccessTokenCreateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccessTokenCreateParams.kt index 38868876..6a89eec0 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccessTokenCreateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccessTokenCreateParams.kt @@ -10,13 +10,12 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional @@ -28,20 +27,56 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun code(): String = body.code() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun clientId(): Optional = body.clientId() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun clientSecret(): Optional = body.clientSecret() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun redirectUri(): Optional = body.redirectUri() + /** + * Returns the raw JSON value of [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected type. + */ fun _code(): JsonField = body._code() + /** + * Returns the raw JSON value of [clientId]. + * + * Unlike [clientId], this method doesn't throw if the JSON field has an unexpected type. + */ fun _clientId(): JsonField = body._clientId() + /** + * Returns the raw JSON value of [clientSecret]. + * + * Unlike [clientSecret], this method doesn't throw if the JSON field has an unexpected type. + */ fun _clientSecret(): JsonField = body._clientSecret() + /** + * Returns the raw JSON value of [redirectUri]. + * + * Unlike [redirectUri], this method doesn't throw if the JSON field has an unexpected type. + */ fun _redirectUri(): JsonField = body._redirectUri() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -50,173 +85,22 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("code") - @ExcludeMissing - private val code: JsonField = JsonMissing.of(), - @JsonProperty("client_id") - @ExcludeMissing - private val clientId: JsonField = JsonMissing.of(), - @JsonProperty("client_secret") - @ExcludeMissing - private val clientSecret: JsonField = JsonMissing.of(), - @JsonProperty("redirect_uri") - @ExcludeMissing - private val redirectUri: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun code(): String = code.getRequired("code") - - fun clientId(): Optional = Optional.ofNullable(clientId.getNullable("client_id")) - - fun clientSecret(): Optional = - Optional.ofNullable(clientSecret.getNullable("client_secret")) - - fun redirectUri(): Optional = - Optional.ofNullable(redirectUri.getNullable("redirect_uri")) - - @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code - - @JsonProperty("client_id") @ExcludeMissing fun _clientId(): JsonField = clientId - - @JsonProperty("client_secret") - @ExcludeMissing - fun _clientSecret(): JsonField = clientSecret - - @JsonProperty("redirect_uri") - @ExcludeMissing - fun _redirectUri(): JsonField = redirectUri - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - code() - clientId() - clientSecret() - redirectUri() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var code: JsonField? = null - private var clientId: JsonField = JsonMissing.of() - private var clientSecret: JsonField = JsonMissing.of() - private var redirectUri: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - code = body.code - clientId = body.clientId - clientSecret = body.clientSecret - redirectUri = body.redirectUri - additionalProperties = body.additionalProperties.toMutableMap() - } - - fun code(code: String) = code(JsonField.of(code)) - - fun code(code: JsonField) = apply { this.code = code } - - fun clientId(clientId: String) = clientId(JsonField.of(clientId)) - - fun clientId(clientId: JsonField) = apply { this.clientId = clientId } - - fun clientSecret(clientSecret: String) = clientSecret(JsonField.of(clientSecret)) - - fun clientSecret(clientSecret: JsonField) = apply { - this.clientSecret = clientSecret - } - - fun redirectUri(redirectUri: String) = redirectUri(JsonField.of(redirectUri)) - - fun redirectUri(redirectUri: JsonField) = apply { - this.redirectUri = redirectUri - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = - Body( - checkRequired("code", code), - clientId, - clientSecret, - redirectUri, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && code == other.code && clientId == other.clientId && clientSecret == other.clientSecret && redirectUri == other.redirectUri && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(code, clientId, clientSecret, redirectUri, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{code=$code, clientId=$clientId, clientSecret=$clientSecret, redirectUri=$redirectUri, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [AccessTokenCreateParams]. + * + * The following fields are required: + * ```java + * .code() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [AccessTokenCreateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -230,22 +114,60 @@ private constructor( additionalQueryParams = accessTokenCreateParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [code] + * - [clientId] + * - [clientSecret] + * - [redirectUri] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + fun code(code: String) = apply { body.code(code) } + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun code(code: JsonField) = apply { body.code(code) } fun clientId(clientId: String) = apply { body.clientId(clientId) } + /** + * Sets [Builder.clientId] to an arbitrary JSON value. + * + * You should usually call [Builder.clientId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun clientId(clientId: JsonField) = apply { body.clientId(clientId) } fun clientSecret(clientSecret: String) = apply { body.clientSecret(clientSecret) } + /** + * Sets [Builder.clientSecret] to an arbitrary JSON value. + * + * You should usually call [Builder.clientSecret] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun clientSecret(clientSecret: JsonField) = apply { body.clientSecret(clientSecret) } fun redirectUri(redirectUri: String) = apply { body.redirectUri(redirectUri) } + /** + * Sets [Builder.redirectUri] to an arbitrary JSON value. + * + * You should usually call [Builder.redirectUri] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun redirectUri(redirectUri: JsonField) = apply { body.redirectUri(redirectUri) } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { @@ -365,6 +287,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [AccessTokenCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .code() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): AccessTokenCreateParams = AccessTokenCreateParams( body.build(), @@ -373,6 +307,277 @@ private constructor( ) } + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val code: JsonField, + private val clientId: JsonField, + private val clientSecret: JsonField, + private val redirectUri: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("code") @ExcludeMissing code: JsonField = JsonMissing.of(), + @JsonProperty("client_id") + @ExcludeMissing + clientId: JsonField = JsonMissing.of(), + @JsonProperty("client_secret") + @ExcludeMissing + clientSecret: JsonField = JsonMissing.of(), + @JsonProperty("redirect_uri") + @ExcludeMissing + redirectUri: JsonField = JsonMissing.of(), + ) : this(code, clientId, clientSecret, redirectUri, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun code(): String = code.getRequired("code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun clientId(): Optional = clientId.getOptional("client_id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun clientSecret(): Optional = clientSecret.getOptional("client_secret") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun redirectUri(): Optional = redirectUri.getOptional("redirect_uri") + + /** + * Returns the raw JSON value of [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code + + /** + * Returns the raw JSON value of [clientId]. + * + * Unlike [clientId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("client_id") @ExcludeMissing fun _clientId(): JsonField = clientId + + /** + * Returns the raw JSON value of [clientSecret]. + * + * Unlike [clientSecret], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("client_secret") + @ExcludeMissing + fun _clientSecret(): JsonField = clientSecret + + /** + * Returns the raw JSON value of [redirectUri]. + * + * Unlike [redirectUri], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("redirect_uri") + @ExcludeMissing + fun _redirectUri(): JsonField = redirectUri + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .code() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var code: JsonField? = null + private var clientId: JsonField = JsonMissing.of() + private var clientSecret: JsonField = JsonMissing.of() + private var redirectUri: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + code = body.code + clientId = body.clientId + clientSecret = body.clientSecret + redirectUri = body.redirectUri + additionalProperties = body.additionalProperties.toMutableMap() + } + + fun code(code: String) = code(JsonField.of(code)) + + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun code(code: JsonField) = apply { this.code = code } + + fun clientId(clientId: String) = clientId(JsonField.of(clientId)) + + /** + * Sets [Builder.clientId] to an arbitrary JSON value. + * + * You should usually call [Builder.clientId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun clientId(clientId: JsonField) = apply { this.clientId = clientId } + + fun clientSecret(clientSecret: String) = clientSecret(JsonField.of(clientSecret)) + + /** + * Sets [Builder.clientSecret] to an arbitrary JSON value. + * + * You should usually call [Builder.clientSecret] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun clientSecret(clientSecret: JsonField) = apply { + this.clientSecret = clientSecret + } + + fun redirectUri(redirectUri: String) = redirectUri(JsonField.of(redirectUri)) + + /** + * Sets [Builder.redirectUri] to an arbitrary JSON value. + * + * You should usually call [Builder.redirectUri] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun redirectUri(redirectUri: JsonField) = apply { + this.redirectUri = redirectUri + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .code() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("code", code), + clientId, + clientSecret, + redirectUri, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + code() + clientId() + clientSecret() + redirectUri() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (code.asKnown().isPresent) 1 else 0) + + (if (clientId.asKnown().isPresent) 1 else 0) + + (if (clientSecret.asKnown().isPresent) 1 else 0) + + (if (redirectUri.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && code == other.code && clientId == other.clientId && clientSecret == other.clientSecret && redirectUri == other.redirectUri && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(code, clientId, clientSecret, redirectUri, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{code=$code, clientId=$clientId, clientSecret=$clientSecret, redirectUri=$redirectUri, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountCreateResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountCreateResponse.kt index fbbf3441..e54605fa 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountCreateResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountCreateResponse.kt @@ -11,115 +11,197 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class AccountCreateResponse -@JsonCreator private constructor( - @JsonProperty("access_token") - @ExcludeMissing - private val accessToken: JsonField = JsonMissing.of(), - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("authentication_type") - @ExcludeMissing - private val authenticationType: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("products") - @ExcludeMissing - private val products: JsonField> = JsonMissing.of(), - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accessToken: JsonField, + private val accountId: JsonField, + private val authenticationType: JsonField, + private val companyId: JsonField, + private val connectionId: JsonField, + private val products: JsonField>, + private val providerId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("access_token") + @ExcludeMissing + accessToken: JsonField = JsonMissing.of(), + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("authentication_type") + @ExcludeMissing + authenticationType: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("products") + @ExcludeMissing + products: JsonField> = JsonMissing.of(), + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + ) : this( + accessToken, + accountId, + authenticationType, + companyId, + connectionId, + products, + providerId, + mutableMapOf(), + ) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun accessToken(): String = accessToken.getRequired("access_token") - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * [DEPRECATED] Use `connection_id` to associate a connection with an access token + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun authenticationType(): AuthenticationType = authenticationType.getRequired("authentication_type") - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * [DEPRECATED] Use `connection_id` to associate a connection with an access token + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") - /** The ID of the new connection */ + /** + * The ID of the new connection + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun connectionId(): String = connectionId.getRequired("connection_id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun products(): List = products.getRequired("products") - /** The ID of the provider associated with the `access_token` */ + /** + * The ID of the provider associated with the `access_token` + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun providerId(): String = providerId.getRequired("provider_id") + /** + * Returns the raw JSON value of [accessToken]. + * + * Unlike [accessToken], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("access_token") @ExcludeMissing fun _accessToken(): JsonField = accessToken - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. + */ @Deprecated("deprecated") @JsonProperty("account_id") @ExcludeMissing fun _accountId(): JsonField = accountId + /** + * Returns the raw JSON value of [authenticationType]. + * + * Unlike [authenticationType], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("authentication_type") @ExcludeMissing fun _authenticationType(): JsonField = authenticationType - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. + */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - /** The ID of the new connection */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("products") @ExcludeMissing fun _products(): JsonField> = products - /** The ID of the provider associated with the `access_token` */ + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("provider_id") @ExcludeMissing fun _providerId(): JsonField = providerId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AccountCreateResponse = apply { - if (validated) { - return@apply - } - - accessToken() - accountId() - authenticationType() - companyId() - connectionId() - products() - providerId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [AccountCreateResponse]. + * + * The following fields are required: + * ```java + * .accessToken() + * .accountId() + * .authenticationType() + * .companyId() + * .connectionId() + * .products() + * .providerId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -149,19 +231,39 @@ private constructor( fun accessToken(accessToken: String) = accessToken(JsonField.of(accessToken)) + /** + * Sets [Builder.accessToken] to an arbitrary JSON value. + * + * You should usually call [Builder.accessToken] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun accessToken(accessToken: JsonField) = apply { this.accessToken = accessToken } /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ @Deprecated("deprecated") fun accountId(accountId: String) = accountId(JsonField.of(accountId)) - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } fun authenticationType(authenticationType: AuthenticationType) = authenticationType(JsonField.of(authenticationType)) + /** + * Sets [Builder.authenticationType] to an arbitrary JSON value. + * + * You should usually call [Builder.authenticationType] with a well-typed + * [AuthenticationType] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun authenticationType(authenticationType: JsonField) = apply { this.authenticationType = authenticationType } @@ -170,41 +272,65 @@ private constructor( @Deprecated("deprecated") fun companyId(companyId: String) = companyId(JsonField.of(companyId)) - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } /** The ID of the new connection */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** The ID of the new connection */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } fun products(products: List) = products(JsonField.of(products)) + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun products(products: JsonField>) = apply { this.products = products.map { it.toMutableList() } } + /** + * Adds a single [String] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addProduct(product: String) = apply { products = - (products ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(product) + (products ?: JsonField.of(mutableListOf())).also { + checkKnown("products", it).add(product) } } /** The ID of the provider associated with the `access_token` */ fun providerId(providerId: String) = providerId(JsonField.of(providerId)) - /** The ID of the provider associated with the `access_token` */ + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun providerId(providerId: JsonField) = apply { this.providerId = providerId } fun additionalProperties(additionalProperties: Map) = apply { @@ -226,6 +352,24 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [AccountCreateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accessToken() + * .accountId() + * .authenticationType() + * .companyId() + * .connectionId() + * .products() + * .providerId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): AccountCreateResponse = AccountCreateResponse( checkRequired("accessToken", accessToken), @@ -235,10 +379,50 @@ private constructor( checkRequired("connectionId", connectionId), checkRequired("products", products).map { it.toImmutable() }, checkRequired("providerId", providerId), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): AccountCreateResponse = apply { + if (validated) { + return@apply + } + + accessToken() + accountId() + authenticationType().validate() + companyId() + connectionId() + products() + providerId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accessToken.asKnown().isPresent) 1 else 0) + + (if (accountId.asKnown().isPresent) 1 else 0) + + (authenticationType.asKnown().getOrNull()?.validity() ?: 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + + (products.asKnown().getOrNull()?.size ?: 0) + + (if (providerId.asKnown().isPresent) 1 else 0) + class AuthenticationType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -340,6 +524,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): AuthenticationType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountDisconnectParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountDisconnectParams.kt index 1e95395e..20b1623d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountDisconnectParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountDisconnectParams.kt @@ -3,7 +3,6 @@ package com.tryfinch.api.models import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams @@ -19,19 +18,11 @@ private constructor( private val additionalBodyProperties: Map, ) : Params { - fun _additionalHeaders(): Headers = additionalHeaders - - fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalBodyProperties(): Map = additionalBodyProperties - @JvmSynthetic - internal fun _body(): Optional> = - Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - - override fun _headers(): Headers = additionalHeaders + fun _additionalHeaders(): Headers = additionalHeaders - override fun _queryParams(): QueryParams = additionalQueryParams + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) @@ -39,11 +30,11 @@ private constructor( @JvmStatic fun none(): AccountDisconnectParams = builder().build() + /** Returns a mutable builder for constructing an instance of [AccountDisconnectParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [AccountDisconnectParams]. */ - @NoAutoDetect class Builder internal constructor() { private var additionalHeaders: Headers.Builder = Headers.builder() @@ -178,6 +169,11 @@ private constructor( keys.forEach(::removeAdditionalBodyProperty) } + /** + * Returns an immutable instance of [AccountDisconnectParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): AccountDisconnectParams = AccountDisconnectParams( additionalHeaders.build(), @@ -186,6 +182,13 @@ private constructor( ) } + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountIntrospectParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountIntrospectParams.kt index c9718b4c..946ad406 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountIntrospectParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountIntrospectParams.kt @@ -2,7 +2,6 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams @@ -19,21 +18,17 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): AccountIntrospectParams = builder().build() + /** Returns a mutable builder for constructing an instance of [AccountIntrospectParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [AccountIntrospectParams]. */ - @NoAutoDetect class Builder internal constructor() { private var additionalHeaders: Headers.Builder = Headers.builder() @@ -143,10 +138,19 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [AccountIntrospectParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): AccountIntrospectParams = AccountIntrospectParams(additionalHeaders.build(), additionalQueryParams.build()) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountUpdateEvent.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountUpdateEvent.kt index 5925dc19..e6305b42 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountUpdateEvent.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountUpdateEvent.kt @@ -11,57 +11,85 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class AccountUpdateEvent -@JsonCreator private constructor( - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("data") @ExcludeMissing private val data: JsonField = JsonMissing.of(), - @JsonProperty("event_type") - @ExcludeMissing - private val eventType: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accountId: JsonField, + private val companyId: JsonField, + private val connectionId: JsonField, + private val data: JsonField, + private val eventType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("event_type") + @ExcludeMissing + eventType: JsonField = JsonMissing.of(), + ) : this(accountId, companyId, connectionId, data, eventType, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder() + .accountId(accountId) + .companyId(companyId) + .connectionId(connectionId) + .build() + /** * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") /** * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") - /** Unique Finch ID of the connection associated with the webhook event. */ - fun connectionId(): Optional = - Optional.ofNullable(connectionId.getNullable("connection_id")) + /** + * Unique Finch ID of the connection associated with the webhook event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun connectionId(): Optional = connectionId.getOptional("connection_id") - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") - fun eventType(): Optional = Optional.ofNullable(eventType.getNullable("event_type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun eventType(): Optional = eventType.getOptional("event_type") /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("account_id") @@ -69,53 +97,61 @@ private constructor( fun _accountId(): JsonField = accountId /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [eventType]. + * + * Unlike [eventType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("event_type") @ExcludeMissing fun _eventType(): JsonField = eventType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBaseWebhookEvent(): BaseWebhookEvent = - BaseWebhookEvent.builder() - .accountId(accountId) - .companyId(companyId) - .connectionId(connectionId) - .build() - - private var validated: Boolean = false - - fun validate(): AccountUpdateEvent = apply { - if (validated) { - return@apply - } - - accountId() - companyId() - connectionId() - data().ifPresent { it.validate() } - eventType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [AccountUpdateEvent]. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -147,8 +183,11 @@ private constructor( fun accountId(accountId: String) = accountId(JsonField.of(accountId)) /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } @@ -161,8 +200,11 @@ private constructor( fun companyId(companyId: String) = companyId(JsonField.of(companyId)) /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } @@ -170,17 +212,36 @@ private constructor( /** Unique Finch ID of the connection associated with the webhook event. */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } fun data(data: Data) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun eventType(eventType: EventType) = eventType(JsonField.of(eventType)) + /** + * Sets [Builder.eventType] to an arbitrary JSON value. + * + * You should usually call [Builder.eventType] with a well-typed [EventType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun eventType(eventType: JsonField) = apply { this.eventType = eventType } fun additionalProperties(additionalProperties: Map) = apply { @@ -202,6 +263,19 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [AccountUpdateEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): AccountUpdateEvent = AccountUpdateEvent( checkRequired("accountId", accountId), @@ -209,57 +283,118 @@ private constructor( connectionId, data, eventType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): AccountUpdateEvent = apply { + if (validated) { + return@apply + } + + accountId() + companyId() + connectionId() + data().ifPresent { it.validate() } + eventType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountId.asKnown().isPresent) 1 else 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (eventType.asKnown().getOrNull()?.validity() ?: 0) + class Data - @JsonCreator private constructor( - @JsonProperty("authentication_method") - @ExcludeMissing - private val authenticationMethod: JsonField = JsonMissing.of(), - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val authenticationMethod: JsonField, + private val status: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("authentication_method") + @ExcludeMissing + authenticationMethod: JsonField = JsonMissing.of(), + @JsonProperty("status") + @ExcludeMissing + status: JsonField = JsonMissing.of(), + ) : this(authenticationMethod, status, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ fun authenticationMethod(): AuthenticationMethod = authenticationMethod.getRequired("authentication_method") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ fun status(): ConnectionStatusType = status.getRequired("status") + /** + * Returns the raw JSON value of [authenticationMethod]. + * + * Unlike [authenticationMethod], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("authentication_method") @ExcludeMissing fun _authenticationMethod(): JsonField = authenticationMethod + /** + * Returns the raw JSON value of [status]. + * + * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Data = apply { - if (validated) { - return@apply - } - - authenticationMethod().validate() - status() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Data]. + * + * The following fields are required: + * ```java + * .authenticationMethod() + * .status() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -280,6 +415,13 @@ private constructor( fun authenticationMethod(authenticationMethod: AuthenticationMethod) = authenticationMethod(JsonField.of(authenticationMethod)) + /** + * Sets [Builder.authenticationMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authenticationMethod] with a well-typed + * [AuthenticationMethod] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun authenticationMethod(authenticationMethod: JsonField) = apply { this.authenticationMethod = authenticationMethod @@ -287,6 +429,13 @@ private constructor( fun status(status: ConnectionStatusType) = status(JsonField.of(status)) + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [ConnectionStatusType] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun status(status: JsonField) = apply { this.status = status } fun additionalProperties(additionalProperties: Map) = apply { @@ -308,82 +457,148 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .authenticationMethod() + * .status() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Data = Data( checkRequired("authenticationMethod", authenticationMethod), checkRequired("status", status), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + authenticationMethod().validate() + status().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (authenticationMethod.asKnown().getOrNull()?.validity() ?: 0) + + (status.asKnown().getOrNull()?.validity() ?: 0) + class AuthenticationMethod - @JsonCreator private constructor( - @JsonProperty("benefits_support") - @ExcludeMissing - private val benefitsSupport: JsonField = JsonMissing.of(), - @JsonProperty("supported_fields") - @ExcludeMissing - private val supportedFields: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val benefitsSupport: JsonField, + private val supportedFields: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("benefits_support") + @ExcludeMissing + benefitsSupport: JsonField = JsonMissing.of(), + @JsonProperty("supported_fields") + @ExcludeMissing + supportedFields: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(benefitsSupport, supportedFields, type, mutableMapOf()) + /** * Each benefit type and their supported features. If the benefit type is not supported, * the property will be null + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ fun benefitsSupport(): Optional = - Optional.ofNullable(benefitsSupport.getNullable("benefits_support")) + benefitsSupport.getOptional("benefits_support") - /** The supported data fields returned by our HR and payroll endpoints */ + /** + * The supported data fields returned by our HR and payroll endpoints + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun supportedFields(): Optional = - Optional.ofNullable(supportedFields.getNullable("supported_fields")) + supportedFields.getOptional("supported_fields") - /** The type of authentication method. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The type of authentication method. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") /** - * Each benefit type and their supported features. If the benefit type is not supported, - * the property will be null + * Returns the raw JSON value of [benefitsSupport]. + * + * Unlike [benefitsSupport], this method doesn't throw if the JSON field has an + * unexpected type. */ @JsonProperty("benefits_support") @ExcludeMissing fun _benefitsSupport(): JsonField = benefitsSupport - /** The supported data fields returned by our HR and payroll endpoints */ + /** + * Returns the raw JSON value of [supportedFields]. + * + * Unlike [supportedFields], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("supported_fields") @ExcludeMissing fun _supportedFields(): JsonField = supportedFields - /** The type of authentication method. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AuthenticationMethod = apply { - if (validated) { - return@apply - } - - benefitsSupport().ifPresent { it.validate() } - supportedFields().ifPresent { it.validate() } - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [AuthenticationMethod]. + */ @JvmStatic fun builder() = Builder() } @@ -411,15 +626,17 @@ private constructor( benefitsSupport(JsonField.ofNullable(benefitsSupport)) /** - * Each benefit type and their supported features. If the benefit type is not - * supported, the property will be null + * Alias for calling [Builder.benefitsSupport] with `benefitsSupport.orElse(null)`. */ fun benefitsSupport(benefitsSupport: Optional) = - benefitsSupport(benefitsSupport.orElse(null)) + benefitsSupport(benefitsSupport.getOrNull()) /** - * Each benefit type and their supported features. If the benefit type is not - * supported, the property will be null + * Sets [Builder.benefitsSupport] to an arbitrary JSON value. + * + * You should usually call [Builder.benefitsSupport] with a well-typed + * [BenefitsSupport] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. */ fun benefitsSupport(benefitsSupport: JsonField) = apply { this.benefitsSupport = benefitsSupport @@ -429,11 +646,19 @@ private constructor( fun supportedFields(supportedFields: SupportedFields?) = supportedFields(JsonField.ofNullable(supportedFields)) - /** The supported data fields returned by our HR and payroll endpoints */ + /** + * Alias for calling [Builder.supportedFields] with `supportedFields.orElse(null)`. + */ fun supportedFields(supportedFields: Optional) = - supportedFields(supportedFields.orElse(null)) + supportedFields(supportedFields.getOrNull()) - /** The supported data fields returned by our HR and payroll endpoints */ + /** + * Sets [Builder.supportedFields] to an arbitrary JSON value. + * + * You should usually call [Builder.supportedFields] with a well-typed + * [SupportedFields] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun supportedFields(supportedFields: JsonField) = apply { this.supportedFields = supportedFields } @@ -441,7 +666,13 @@ private constructor( /** The type of authentication method. */ fun type(type: Type) = type(JsonField.of(type)) - /** The type of authentication method. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -466,119 +697,234 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [AuthenticationMethod]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): AuthenticationMethod = AuthenticationMethod( benefitsSupport, supportedFields, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): AuthenticationMethod = apply { + if (validated) { + return@apply + } + + benefitsSupport().ifPresent { it.validate() } + supportedFields().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (benefitsSupport.asKnown().getOrNull()?.validity() ?: 0) + + (supportedFields.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + /** The supported data fields returned by our HR and payroll endpoints */ - @NoAutoDetect class SupportedFields - @JsonCreator private constructor( - @JsonProperty("company") - @ExcludeMissing - private val company: JsonField = JsonMissing.of(), - @JsonProperty("directory") - @ExcludeMissing - private val directory: JsonField = JsonMissing.of(), - @JsonProperty("employment") - @ExcludeMissing - private val employment: JsonField = JsonMissing.of(), - @JsonProperty("individual") - @ExcludeMissing - private val individual: JsonField = JsonMissing.of(), - @JsonProperty("pay_group") - @ExcludeMissing - private val payGroup: JsonField = JsonMissing.of(), - @JsonProperty("pay_statement") - @ExcludeMissing - private val payStatement: JsonField = JsonMissing.of(), - @JsonProperty("payment") - @ExcludeMissing - private val payment: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val company: JsonField, + private val directory: JsonField, + private val employment: JsonField, + private val individual: JsonField, + private val payGroup: JsonField, + private val payStatement: JsonField, + private val payment: JsonField, + private val additionalProperties: MutableMap, ) { - fun company(): Optional = - Optional.ofNullable(company.getNullable("company")) + @JsonCreator + private constructor( + @JsonProperty("company") + @ExcludeMissing + company: JsonField = JsonMissing.of(), + @JsonProperty("directory") + @ExcludeMissing + directory: JsonField = JsonMissing.of(), + @JsonProperty("employment") + @ExcludeMissing + employment: JsonField = JsonMissing.of(), + @JsonProperty("individual") + @ExcludeMissing + individual: JsonField = JsonMissing.of(), + @JsonProperty("pay_group") + @ExcludeMissing + payGroup: JsonField = JsonMissing.of(), + @JsonProperty("pay_statement") + @ExcludeMissing + payStatement: JsonField = JsonMissing.of(), + @JsonProperty("payment") + @ExcludeMissing + payment: JsonField = JsonMissing.of(), + ) : this( + company, + directory, + employment, + individual, + payGroup, + payStatement, + payment, + mutableMapOf(), + ) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun company(): Optional = company.getOptional("company") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ fun directory(): Optional = - Optional.ofNullable(directory.getNullable("directory")) + directory.getOptional("directory") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ fun employment(): Optional = - Optional.ofNullable(employment.getNullable("employment")) + employment.getOptional("employment") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ fun individual(): Optional = - Optional.ofNullable(individual.getNullable("individual")) + individual.getOptional("individual") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ fun payGroup(): Optional = - Optional.ofNullable(payGroup.getNullable("pay_group")) + payGroup.getOptional("pay_group") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ fun payStatement(): Optional = - Optional.ofNullable(payStatement.getNullable("pay_statement")) + payStatement.getOptional("pay_statement") - fun payment(): Optional = - Optional.ofNullable(payment.getNullable("payment")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun payment(): Optional = payment.getOptional("payment") + /** + * Returns the raw JSON value of [company]. + * + * Unlike [company], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("company") @ExcludeMissing fun _company(): JsonField = company + /** + * Returns the raw JSON value of [directory]. + * + * Unlike [directory], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("directory") @ExcludeMissing fun _directory(): JsonField = directory + /** + * Returns the raw JSON value of [employment]. + * + * Unlike [employment], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("employment") @ExcludeMissing fun _employment(): JsonField = employment + /** + * Returns the raw JSON value of [individual]. + * + * Unlike [individual], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("individual") @ExcludeMissing fun _individual(): JsonField = individual + /** + * Returns the raw JSON value of [payGroup]. + * + * Unlike [payGroup], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("pay_group") @ExcludeMissing fun _payGroup(): JsonField = payGroup + /** + * Returns the raw JSON value of [payStatement]. + * + * Unlike [payStatement], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("pay_statement") @ExcludeMissing fun _payStatement(): JsonField = payStatement + /** + * Returns the raw JSON value of [payment]. + * + * Unlike [payment], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("payment") @ExcludeMissing fun _payment(): JsonField = payment + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedFields = apply { - if (validated) { - return@apply - } - - company().ifPresent { it.validate() } - directory().ifPresent { it.validate() } - employment().ifPresent { it.validate() } - individual().ifPresent { it.validate() } - payGroup().ifPresent { it.validate() } - payStatement().ifPresent { it.validate() } - payment().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [SupportedFields]. + */ @JvmStatic fun builder() = Builder() } @@ -609,6 +955,13 @@ private constructor( fun company(company: SupportedCompanyFields) = company(JsonField.of(company)) + /** + * Sets [Builder.company] to an arbitrary JSON value. + * + * You should usually call [Builder.company] with a well-typed + * [SupportedCompanyFields] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ fun company(company: JsonField) = apply { this.company = company } @@ -616,6 +969,13 @@ private constructor( fun directory(directory: SupportedDirectoryFields) = directory(JsonField.of(directory)) + /** + * Sets [Builder.directory] to an arbitrary JSON value. + * + * You should usually call [Builder.directory] with a well-typed + * [SupportedDirectoryFields] value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ fun directory(directory: JsonField) = apply { this.directory = directory } @@ -623,6 +983,13 @@ private constructor( fun employment(employment: SupportedEmploymentFields) = employment(JsonField.of(employment)) + /** + * Sets [Builder.employment] to an arbitrary JSON value. + * + * You should usually call [Builder.employment] with a well-typed + * [SupportedEmploymentFields] value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ fun employment(employment: JsonField) = apply { this.employment = employment } @@ -630,6 +997,13 @@ private constructor( fun individual(individual: SupportedIndividualFields) = individual(JsonField.of(individual)) + /** + * Sets [Builder.individual] to an arbitrary JSON value. + * + * You should usually call [Builder.individual] with a well-typed + * [SupportedIndividualFields] value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ fun individual(individual: JsonField) = apply { this.individual = individual } @@ -637,6 +1011,13 @@ private constructor( fun payGroup(payGroup: SupportedPayGroupFields) = payGroup(JsonField.of(payGroup)) + /** + * Sets [Builder.payGroup] to an arbitrary JSON value. + * + * You should usually call [Builder.payGroup] with a well-typed + * [SupportedPayGroupFields] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ fun payGroup(payGroup: JsonField) = apply { this.payGroup = payGroup } @@ -644,12 +1025,26 @@ private constructor( fun payStatement(payStatement: SupportedPayStatementFields) = payStatement(JsonField.of(payStatement)) + /** + * Sets [Builder.payStatement] to an arbitrary JSON value. + * + * You should usually call [Builder.payStatement] with a well-typed + * [SupportedPayStatementFields] value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ fun payStatement(payStatement: JsonField) = apply { this.payStatement = payStatement } fun payment(payment: SupportedPaymentFields) = payment(JsonField.of(payment)) + /** + * Sets [Builder.payment] to an arbitrary JSON value. + * + * You should usually call [Builder.payment] with a well-typed + * [SupportedPaymentFields] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ fun payment(payment: JsonField) = apply { this.payment = payment } @@ -676,6 +1071,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedFields = SupportedFields( company, @@ -685,129 +1085,268 @@ private constructor( payGroup, payStatement, payment, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): SupportedFields = apply { + if (validated) { + return@apply + } + + company().ifPresent { it.validate() } + directory().ifPresent { it.validate() } + employment().ifPresent { it.validate() } + individual().ifPresent { it.validate() } + payGroup().ifPresent { it.validate() } + payStatement().ifPresent { it.validate() } + payment().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (company.asKnown().getOrNull()?.validity() ?: 0) + + (directory.asKnown().getOrNull()?.validity() ?: 0) + + (employment.asKnown().getOrNull()?.validity() ?: 0) + + (individual.asKnown().getOrNull()?.validity() ?: 0) + + (payGroup.asKnown().getOrNull()?.validity() ?: 0) + + (payStatement.asKnown().getOrNull()?.validity() ?: 0) + + (payment.asKnown().getOrNull()?.validity() ?: 0) + class SupportedCompanyFields - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("accounts") - @ExcludeMissing - private val accounts: JsonField = JsonMissing.of(), - @JsonProperty("departments") - @ExcludeMissing - private val departments: JsonField = JsonMissing.of(), - @JsonProperty("ein") - @ExcludeMissing - private val ein: JsonField = JsonMissing.of(), - @JsonProperty("entity") - @ExcludeMissing - private val entity: JsonField = JsonMissing.of(), - @JsonProperty("legal_name") - @ExcludeMissing - private val legalName: JsonField = JsonMissing.of(), - @JsonProperty("locations") - @ExcludeMissing - private val locations: JsonField = JsonMissing.of(), - @JsonProperty("primary_email") - @ExcludeMissing - private val primaryEmail: JsonField = JsonMissing.of(), - @JsonProperty("primary_phone_number") - @ExcludeMissing - private val primaryPhoneNumber: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val accounts: JsonField, + private val departments: JsonField, + private val ein: JsonField, + private val entity: JsonField, + private val legalName: JsonField, + private val locations: JsonField, + private val primaryEmail: JsonField, + private val primaryPhoneNumber: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") + @ExcludeMissing + id: JsonField = JsonMissing.of(), + @JsonProperty("accounts") + @ExcludeMissing + accounts: JsonField = JsonMissing.of(), + @JsonProperty("departments") + @ExcludeMissing + departments: JsonField = JsonMissing.of(), + @JsonProperty("ein") + @ExcludeMissing + ein: JsonField = JsonMissing.of(), + @JsonProperty("entity") + @ExcludeMissing + entity: JsonField = JsonMissing.of(), + @JsonProperty("legal_name") + @ExcludeMissing + legalName: JsonField = JsonMissing.of(), + @JsonProperty("locations") + @ExcludeMissing + locations: JsonField = JsonMissing.of(), + @JsonProperty("primary_email") + @ExcludeMissing + primaryEmail: JsonField = JsonMissing.of(), + @JsonProperty("primary_phone_number") + @ExcludeMissing + primaryPhoneNumber: JsonField = JsonMissing.of(), + ) : this( + id, + accounts, + departments, + ein, + entity, + legalName, + locations, + primaryEmail, + primaryPhoneNumber, + mutableMapOf(), + ) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") - fun accounts(): Optional = - Optional.ofNullable(accounts.getNullable("accounts")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun accounts(): Optional = accounts.getOptional("accounts") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun departments(): Optional = - Optional.ofNullable(departments.getNullable("departments")) + departments.getOptional("departments") - fun ein(): Optional = Optional.ofNullable(ein.getNullable("ein")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun ein(): Optional = ein.getOptional("ein") - fun entity(): Optional = - Optional.ofNullable(entity.getNullable("entity")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun entity(): Optional = entity.getOptional("entity") - fun legalName(): Optional = - Optional.ofNullable(legalName.getNullable("legal_name")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun legalName(): Optional = legalName.getOptional("legal_name") - fun locations(): Optional = - Optional.ofNullable(locations.getNullable("locations")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun locations(): Optional = locations.getOptional("locations") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun primaryEmail(): Optional = - Optional.ofNullable(primaryEmail.getNullable("primary_email")) + primaryEmail.getOptional("primary_email") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun primaryPhoneNumber(): Optional = - Optional.ofNullable(primaryPhoneNumber.getNullable("primary_phone_number")) + primaryPhoneNumber.getOptional("primary_phone_number") + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [accounts]. + * + * Unlike [accounts], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("accounts") @ExcludeMissing fun _accounts(): JsonField = accounts + /** + * Returns the raw JSON value of [departments]. + * + * Unlike [departments], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("departments") @ExcludeMissing fun _departments(): JsonField = departments + /** + * Returns the raw JSON value of [ein]. + * + * Unlike [ein], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("ein") @ExcludeMissing fun _ein(): JsonField = ein + /** + * Returns the raw JSON value of [entity]. + * + * Unlike [entity], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("entity") @ExcludeMissing fun _entity(): JsonField = entity + /** + * Returns the raw JSON value of [legalName]. + * + * Unlike [legalName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("legal_name") @ExcludeMissing fun _legalName(): JsonField = legalName + /** + * Returns the raw JSON value of [locations]. + * + * Unlike [locations], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("locations") @ExcludeMissing fun _locations(): JsonField = locations + /** + * Returns the raw JSON value of [primaryEmail]. + * + * Unlike [primaryEmail], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("primary_email") @ExcludeMissing fun _primaryEmail(): JsonField = primaryEmail + /** + * Returns the raw JSON value of [primaryPhoneNumber]. + * + * Unlike [primaryPhoneNumber], this method doesn't throw if the JSON field has + * an unexpected type. + */ @JsonProperty("primary_phone_number") @ExcludeMissing fun _primaryPhoneNumber(): JsonField = primaryPhoneNumber + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedCompanyFields = apply { - if (validated) { - return@apply - } - - id() - accounts().ifPresent { it.validate() } - departments().ifPresent { it.validate() } - ein() - entity().ifPresent { it.validate() } - legalName() - locations().ifPresent { it.validate() } - primaryEmail() - primaryPhoneNumber() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedCompanyFields]. + */ @JvmStatic fun builder() = Builder() } @@ -843,10 +1382,24 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun accounts(accounts: Accounts) = accounts(JsonField.of(accounts)) + /** + * Sets [Builder.accounts] to an arbitrary JSON value. + * + * You should usually call [Builder.accounts] with a well-typed [Accounts] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun accounts(accounts: JsonField) = apply { this.accounts = accounts } @@ -854,26 +1407,61 @@ private constructor( fun departments(departments: Departments) = departments(JsonField.of(departments)) + /** + * Sets [Builder.departments] to an arbitrary JSON value. + * + * You should usually call [Builder.departments] with a well-typed + * [Departments] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun departments(departments: JsonField) = apply { this.departments = departments } fun ein(ein: Boolean) = ein(JsonField.of(ein)) + /** + * Sets [Builder.ein] to an arbitrary JSON value. + * + * You should usually call [Builder.ein] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun ein(ein: JsonField) = apply { this.ein = ein } fun entity(entity: Entity) = entity(JsonField.of(entity)) + /** + * Sets [Builder.entity] to an arbitrary JSON value. + * + * You should usually call [Builder.entity] with a well-typed [Entity] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun entity(entity: JsonField) = apply { this.entity = entity } fun legalName(legalName: Boolean) = legalName(JsonField.of(legalName)) + /** + * Sets [Builder.legalName] to an arbitrary JSON value. + * + * You should usually call [Builder.legalName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun legalName(legalName: JsonField) = apply { this.legalName = legalName } fun locations(locations: Locations) = locations(JsonField.of(locations)) + /** + * Sets [Builder.locations] to an arbitrary JSON value. + * + * You should usually call [Builder.locations] with a well-typed [Locations] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun locations(locations: JsonField) = apply { this.locations = locations } @@ -881,6 +1469,13 @@ private constructor( fun primaryEmail(primaryEmail: Boolean) = primaryEmail(JsonField.of(primaryEmail)) + /** + * Sets [Builder.primaryEmail] to an arbitrary JSON value. + * + * You should usually call [Builder.primaryEmail] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun primaryEmail(primaryEmail: JsonField) = apply { this.primaryEmail = primaryEmail } @@ -888,6 +1483,13 @@ private constructor( fun primaryPhoneNumber(primaryPhoneNumber: Boolean) = primaryPhoneNumber(JsonField.of(primaryPhoneNumber)) + /** + * Sets [Builder.primaryPhoneNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.primaryPhoneNumber] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun primaryPhoneNumber(primaryPhoneNumber: JsonField) = apply { this.primaryPhoneNumber = primaryPhoneNumber } @@ -914,6 +1516,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedCompanyFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedCompanyFields = SupportedCompanyFields( id, @@ -925,92 +1532,193 @@ private constructor( locations, primaryEmail, primaryPhoneNumber, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): SupportedCompanyFields = apply { + if (validated) { + return@apply + } + + id() + accounts().ifPresent { it.validate() } + departments().ifPresent { it.validate() } + ein() + entity().ifPresent { it.validate() } + legalName() + locations().ifPresent { it.validate() } + primaryEmail() + primaryPhoneNumber() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (accounts.asKnown().getOrNull()?.validity() ?: 0) + + (departments.asKnown().getOrNull()?.validity() ?: 0) + + (if (ein.asKnown().isPresent) 1 else 0) + + (entity.asKnown().getOrNull()?.validity() ?: 0) + + (if (legalName.asKnown().isPresent) 1 else 0) + + (locations.asKnown().getOrNull()?.validity() ?: 0) + + (if (primaryEmail.asKnown().isPresent) 1 else 0) + + (if (primaryPhoneNumber.asKnown().isPresent) 1 else 0) + class Accounts - @JsonCreator private constructor( - @JsonProperty("account_name") - @ExcludeMissing - private val accountName: JsonField = JsonMissing.of(), - @JsonProperty("account_number") - @ExcludeMissing - private val accountNumber: JsonField = JsonMissing.of(), - @JsonProperty("account_type") - @ExcludeMissing - private val accountType: JsonField = JsonMissing.of(), - @JsonProperty("institution_name") - @ExcludeMissing - private val institutionName: JsonField = JsonMissing.of(), - @JsonProperty("routing_number") - @ExcludeMissing - private val routingNumber: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val accountName: JsonField, + private val accountNumber: JsonField, + private val accountType: JsonField, + private val institutionName: JsonField, + private val routingNumber: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("account_name") + @ExcludeMissing + accountName: JsonField = JsonMissing.of(), + @JsonProperty("account_number") + @ExcludeMissing + accountNumber: JsonField = JsonMissing.of(), + @JsonProperty("account_type") + @ExcludeMissing + accountType: JsonField = JsonMissing.of(), + @JsonProperty("institution_name") + @ExcludeMissing + institutionName: JsonField = JsonMissing.of(), + @JsonProperty("routing_number") + @ExcludeMissing + routingNumber: JsonField = JsonMissing.of(), + ) : this( + accountName, + accountNumber, + accountType, + institutionName, + routingNumber, + mutableMapOf(), + ) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ fun accountName(): Optional = - Optional.ofNullable(accountName.getNullable("account_name")) + accountName.getOptional("account_name") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ fun accountNumber(): Optional = - Optional.ofNullable(accountNumber.getNullable("account_number")) + accountNumber.getOptional("account_number") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ fun accountType(): Optional = - Optional.ofNullable(accountType.getNullable("account_type")) + accountType.getOptional("account_type") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ fun institutionName(): Optional = - Optional.ofNullable(institutionName.getNullable("institution_name")) + institutionName.getOptional("institution_name") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ fun routingNumber(): Optional = - Optional.ofNullable(routingNumber.getNullable("routing_number")) - + routingNumber.getOptional("routing_number") + + /** + * Returns the raw JSON value of [accountName]. + * + * Unlike [accountName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("account_name") @ExcludeMissing fun _accountName(): JsonField = accountName + /** + * Returns the raw JSON value of [accountNumber]. + * + * Unlike [accountNumber], this method doesn't throw if the JSON field has + * an unexpected type. + */ @JsonProperty("account_number") @ExcludeMissing fun _accountNumber(): JsonField = accountNumber + /** + * Returns the raw JSON value of [accountType]. + * + * Unlike [accountType], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("account_type") @ExcludeMissing fun _accountType(): JsonField = accountType + /** + * Returns the raw JSON value of [institutionName]. + * + * Unlike [institutionName], this method doesn't throw if the JSON field has + * an unexpected type. + */ @JsonProperty("institution_name") @ExcludeMissing fun _institutionName(): JsonField = institutionName + /** + * Returns the raw JSON value of [routingNumber]. + * + * Unlike [routingNumber], this method doesn't throw if the JSON field has + * an unexpected type. + */ @JsonProperty("routing_number") @ExcludeMissing fun _routingNumber(): JsonField = routingNumber + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Accounts = apply { - if (validated) { - return@apply - } - - accountName() - accountNumber() - accountType() - institutionName() - routingNumber() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Accounts]. + */ @JvmStatic fun builder() = Builder() } @@ -1038,6 +1746,13 @@ private constructor( fun accountName(accountName: Boolean) = accountName(JsonField.of(accountName)) + /** + * Sets [Builder.accountName] to an arbitrary JSON value. + * + * You should usually call [Builder.accountName] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun accountName(accountName: JsonField) = apply { this.accountName = accountName } @@ -1045,6 +1760,13 @@ private constructor( fun accountNumber(accountNumber: Boolean) = accountNumber(JsonField.of(accountNumber)) + /** + * Sets [Builder.accountNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.accountNumber] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun accountNumber(accountNumber: JsonField) = apply { this.accountNumber = accountNumber } @@ -1052,6 +1774,13 @@ private constructor( fun accountType(accountType: Boolean) = accountType(JsonField.of(accountType)) + /** + * Sets [Builder.accountType] to an arbitrary JSON value. + * + * You should usually call [Builder.accountType] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun accountType(accountType: JsonField) = apply { this.accountType = accountType } @@ -1059,6 +1788,13 @@ private constructor( fun institutionName(institutionName: Boolean) = institutionName(JsonField.of(institutionName)) + /** + * Sets [Builder.institutionName] to an arbitrary JSON value. + * + * You should usually call [Builder.institutionName] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun institutionName(institutionName: JsonField) = apply { this.institutionName = institutionName } @@ -1066,6 +1802,13 @@ private constructor( fun routingNumber(routingNumber: Boolean) = routingNumber(JsonField.of(routingNumber)) + /** + * Sets [Builder.routingNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.routingNumber] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun routingNumber(routingNumber: JsonField) = apply { this.routingNumber = routingNumber } @@ -1092,6 +1835,12 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Accounts]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Accounts = Accounts( accountName, @@ -1099,10 +1848,47 @@ private constructor( accountType, institutionName, routingNumber, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Accounts = apply { + if (validated) { + return@apply + } + + accountName() + accountNumber() + accountType() + institutionName() + routingNumber() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountName.asKnown().isPresent) 1 else 0) + + (if (accountNumber.asKnown().isPresent) 1 else 0) + + (if (accountType.asKnown().isPresent) 1 else 0) + + (if (institutionName.asKnown().isPresent) 1 else 0) + + (if (routingNumber.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1121,53 +1907,71 @@ private constructor( "Accounts{accountName=$accountName, accountNumber=$accountNumber, accountType=$accountType, institutionName=$institutionName, routingNumber=$routingNumber, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Departments - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("parent") - @ExcludeMissing - private val parent: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val name: JsonField, + private val parent: JsonField, + private val additionalProperties: MutableMap, ) { - fun name(): Optional = - Optional.ofNullable(name.getNullable("name")) - - fun parent(): Optional = - Optional.ofNullable(parent.getNullable("parent")) - + @JsonCreator + private constructor( + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("parent") + @ExcludeMissing + parent: JsonField = JsonMissing.of(), + ) : this(name, parent, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun parent(): Optional = parent.getOptional("parent") + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + /** + * Returns the raw JSON value of [parent]. + * + * Unlike [parent], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("parent") @ExcludeMissing fun _parent(): JsonField = parent + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Departments = apply { - if (validated) { - return@apply - } - - name() - parent().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [Departments]. + */ @JvmStatic fun builder() = Builder() } @@ -1189,10 +1993,24 @@ private constructor( fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun parent(parent: Parent) = parent(JsonField.of(parent)) + /** + * Sets [Builder.parent] to an arbitrary JSON value. + * + * You should usually call [Builder.parent] with a well-typed [Parent] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun parent(parent: JsonField) = apply { this.parent = parent } fun additionalProperties(additionalProperties: Map) = @@ -1217,49 +2035,94 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Departments]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Departments = - Departments(name, parent, additionalProperties.toImmutable()) + Departments(name, parent, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Departments = apply { + if (validated) { + return@apply + } + + name() + parent().ifPresent { it.validate() } + validated = true } - @NoAutoDetect + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (parent.asKnown().getOrNull()?.validity() ?: 0) + class Parent - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - fun name(): Optional = - Optional.ofNullable(name.getNullable("name")) - + @JsonCreator + private constructor( + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = - additionalProperties - - private var validated: Boolean = false - - fun validate(): Parent = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [Parent]. + */ @JvmStatic fun builder() = Builder() } @@ -1279,6 +2142,13 @@ private constructor( fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties( @@ -1304,10 +2174,44 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Parent]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Parent = - Parent(name, additionalProperties.toImmutable()) + Parent(name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Parent = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1344,53 +2248,70 @@ private constructor( "Departments{name=$name, parent=$parent, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Entity - @JsonCreator private constructor( - @JsonProperty("subtype") - @ExcludeMissing - private val subtype: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val subtype: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun subtype(): Optional = - Optional.ofNullable(subtype.getNullable("subtype")) - - fun type(): Optional = - Optional.ofNullable(type.getNullable("type")) - + @JsonCreator + private constructor( + @JsonProperty("subtype") + @ExcludeMissing + subtype: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(subtype, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun subtype(): Optional = subtype.getOptional("subtype") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [subtype]. + * + * Unlike [subtype], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Entity = apply { - if (validated) { - return@apply - } - - subtype() - type() - validated = true + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Entity]. + */ @JvmStatic fun builder() = Builder() } @@ -1411,12 +2332,26 @@ private constructor( fun subtype(subtype: Boolean) = subtype(JsonField.of(subtype)) + /** + * Sets [Builder.subtype] to an arbitrary JSON value. + * + * You should usually call [Builder.subtype] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun subtype(subtype: JsonField) = apply { this.subtype = subtype } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = @@ -1441,10 +2376,47 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Entity]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Entity = - Entity(subtype, type, additionalProperties.toImmutable()) + Entity(subtype, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Entity = apply { + if (validated) { + return@apply + } + + subtype() + type() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (subtype.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1463,97 +2435,151 @@ private constructor( "Entity{subtype=$subtype, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Locations - @JsonCreator private constructor( - @JsonProperty("city") - @ExcludeMissing - private val city: JsonField = JsonMissing.of(), - @JsonProperty("country") - @ExcludeMissing - private val country: JsonField = JsonMissing.of(), - @JsonProperty("line1") - @ExcludeMissing - private val line1: JsonField = JsonMissing.of(), - @JsonProperty("line2") - @ExcludeMissing - private val line2: JsonField = JsonMissing.of(), - @JsonProperty("postal_code") - @ExcludeMissing - private val postalCode: JsonField = JsonMissing.of(), - @JsonProperty("state") - @ExcludeMissing - private val state: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val city: JsonField, + private val country: JsonField, + private val line1: JsonField, + private val line2: JsonField, + private val postalCode: JsonField, + private val state: JsonField, + private val additionalProperties: MutableMap, ) { - fun city(): Optional = - Optional.ofNullable(city.getNullable("city")) - - fun country(): Optional = - Optional.ofNullable(country.getNullable("country")) - - fun line1(): Optional = - Optional.ofNullable(line1.getNullable("line1")) - - fun line2(): Optional = - Optional.ofNullable(line2.getNullable("line2")) - - fun postalCode(): Optional = - Optional.ofNullable(postalCode.getNullable("postal_code")) - - fun state(): Optional = - Optional.ofNullable(state.getNullable("state")) - + @JsonCreator + private constructor( + @JsonProperty("city") + @ExcludeMissing + city: JsonField = JsonMissing.of(), + @JsonProperty("country") + @ExcludeMissing + country: JsonField = JsonMissing.of(), + @JsonProperty("line1") + @ExcludeMissing + line1: JsonField = JsonMissing.of(), + @JsonProperty("line2") + @ExcludeMissing + line2: JsonField = JsonMissing.of(), + @JsonProperty("postal_code") + @ExcludeMissing + postalCode: JsonField = JsonMissing.of(), + @JsonProperty("state") + @ExcludeMissing + state: JsonField = JsonMissing.of(), + ) : this(city, country, line1, line2, postalCode, state, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun city(): Optional = city.getOptional("city") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun country(): Optional = country.getOptional("country") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun line1(): Optional = line1.getOptional("line1") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun line2(): Optional = line2.getOptional("line2") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun postalCode(): Optional = postalCode.getOptional("postal_code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun state(): Optional = state.getOptional("state") + + /** + * Returns the raw JSON value of [city]. + * + * Unlike [city], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("city") @ExcludeMissing fun _city(): JsonField = city + /** + * Returns the raw JSON value of [country]. + * + * Unlike [country], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("country") @ExcludeMissing fun _country(): JsonField = country + /** + * Returns the raw JSON value of [line1]. + * + * Unlike [line1], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("line1") @ExcludeMissing fun _line1(): JsonField = line1 + /** + * Returns the raw JSON value of [line2]. + * + * Unlike [line2], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("line2") @ExcludeMissing fun _line2(): JsonField = line2 + /** + * Returns the raw JSON value of [postalCode]. + * + * Unlike [postalCode], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("postal_code") @ExcludeMissing fun _postalCode(): JsonField = postalCode + /** + * Returns the raw JSON value of [state]. + * + * Unlike [state], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("state") @ExcludeMissing fun _state(): JsonField = state + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Locations = apply { - if (validated) { - return@apply - } - - city() - country() - line1() - line2() - postalCode() - state() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [Locations]. + */ @JvmStatic fun builder() = Builder() } @@ -1582,31 +2608,73 @@ private constructor( fun city(city: Boolean) = city(JsonField.of(city)) + /** + * Sets [Builder.city] to an arbitrary JSON value. + * + * You should usually call [Builder.city] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun city(city: JsonField) = apply { this.city = city } fun country(country: Boolean) = country(JsonField.of(country)) + /** + * Sets [Builder.country] to an arbitrary JSON value. + * + * You should usually call [Builder.country] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun country(country: JsonField) = apply { this.country = country } fun line1(line1: Boolean) = line1(JsonField.of(line1)) + /** + * Sets [Builder.line1] to an arbitrary JSON value. + * + * You should usually call [Builder.line1] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun line1(line1: JsonField) = apply { this.line1 = line1 } fun line2(line2: Boolean) = line2(JsonField.of(line2)) + /** + * Sets [Builder.line2] to an arbitrary JSON value. + * + * You should usually call [Builder.line2] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun line2(line2: JsonField) = apply { this.line2 = line2 } fun postalCode(postalCode: Boolean) = postalCode(JsonField.of(postalCode)) + /** + * Sets [Builder.postalCode] to an arbitrary JSON value. + * + * You should usually call [Builder.postalCode] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun postalCode(postalCode: JsonField) = apply { this.postalCode = postalCode } fun state(state: Boolean) = state(JsonField.of(state)) + /** + * Sets [Builder.state] to an arbitrary JSON value. + * + * You should usually call [Builder.state] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun state(state: JsonField) = apply { this.state = state } fun additionalProperties(additionalProperties: Map) = @@ -1631,6 +2699,12 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Locations]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Locations = Locations( city, @@ -1639,10 +2713,49 @@ private constructor( line2, postalCode, state, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Locations = apply { + if (validated) { + return@apply + } + + city() + country() + line1() + line2() + postalCode() + state() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (city.asKnown().isPresent) 1 else 0) + + (if (country.asKnown().isPresent) 1 else 0) + + (if (line1.asKnown().isPresent) 1 else 0) + + (if (line2.asKnown().isPresent) 1 else 0) + + (if (postalCode.asKnown().isPresent) 1 else 0) + + (if (state.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1679,54 +2792,74 @@ private constructor( "SupportedCompanyFields{id=$id, accounts=$accounts, departments=$departments, ein=$ein, entity=$entity, legalName=$legalName, locations=$locations, primaryEmail=$primaryEmail, primaryPhoneNumber=$primaryPhoneNumber, additionalProperties=$additionalProperties}" } - @NoAutoDetect class SupportedDirectoryFields - @JsonCreator private constructor( - @JsonProperty("individuals") - @ExcludeMissing - private val individuals: JsonField = JsonMissing.of(), - @JsonProperty("paging") - @ExcludeMissing - private val paging: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val individuals: JsonField, + private val paging: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("individuals") + @ExcludeMissing + individuals: JsonField = JsonMissing.of(), + @JsonProperty("paging") + @ExcludeMissing + paging: JsonField = JsonMissing.of(), + ) : this(individuals, paging, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun individuals(): Optional = - Optional.ofNullable(individuals.getNullable("individuals")) + individuals.getOptional("individuals") - fun paging(): Optional = - Optional.ofNullable(paging.getNullable("paging")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun paging(): Optional = paging.getOptional("paging") + /** + * Returns the raw JSON value of [individuals]. + * + * Unlike [individuals], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("individuals") @ExcludeMissing fun _individuals(): JsonField = individuals + /** + * Returns the raw JSON value of [paging]. + * + * Unlike [paging], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("paging") @ExcludeMissing fun _paging(): JsonField = paging + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedDirectoryFields = apply { - if (validated) { - return@apply - } - - individuals().ifPresent { it.validate() } - paging().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedDirectoryFields]. + */ @JvmStatic fun builder() = Builder() } @@ -1750,12 +2883,26 @@ private constructor( fun individuals(individuals: Individuals) = individuals(JsonField.of(individuals)) + /** + * Sets [Builder.individuals] to an arbitrary JSON value. + * + * You should usually call [Builder.individuals] with a well-typed + * [Individuals] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun individuals(individuals: JsonField) = apply { this.individuals = individuals } fun paging(paging: Paging) = paging(JsonField.of(paging)) + /** + * Sets [Builder.paging] to an arbitrary JSON value. + * + * You should usually call [Builder.paging] with a well-typed [Paging] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun paging(paging: JsonField) = apply { this.paging = paging } fun additionalProperties(additionalProperties: Map) = @@ -1780,115 +2927,224 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedDirectoryFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedDirectoryFields = SupportedDirectoryFields( individuals, paging, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect - class Individuals - @JsonCreator - private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("department") - @ExcludeMissing - private val department: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("is_active") - @ExcludeMissing - private val isActive: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), - @JsonProperty("manager") - @ExcludeMissing - private val manager: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), - ) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + private var validated: Boolean = false - fun department(): Optional = - Optional.ofNullable(department.getNullable("department")) + fun validate(): SupportedDirectoryFields = apply { + if (validated) { + return@apply + } - fun firstName(): Optional = - Optional.ofNullable(firstName.getNullable("first_name")) + individuals().ifPresent { it.validate() } + paging().ifPresent { it.validate() } + validated = true + } - fun isActive(): Optional = - Optional.ofNullable(isActive.getNullable("is_active")) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } - fun lastName(): Optional = - Optional.ofNullable(lastName.getNullable("last_name")) + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (individuals.asKnown().getOrNull()?.validity() ?: 0) + + (paging.asKnown().getOrNull()?.validity() ?: 0) - fun manager(): Optional = - Optional.ofNullable(manager.getNullable("manager")) + class Individuals + private constructor( + private val id: JsonField, + private val department: JsonField, + private val firstName: JsonField, + private val isActive: JsonField, + private val lastName: JsonField, + private val manager: JsonField, + private val middleName: JsonField, + private val additionalProperties: MutableMap, + ) { - fun middleName(): Optional = - Optional.ofNullable(middleName.getNullable("middle_name")) + @JsonCreator + private constructor( + @JsonProperty("id") + @ExcludeMissing + id: JsonField = JsonMissing.of(), + @JsonProperty("department") + @ExcludeMissing + department: JsonField = JsonMissing.of(), + @JsonProperty("first_name") + @ExcludeMissing + firstName: JsonField = JsonMissing.of(), + @JsonProperty("is_active") + @ExcludeMissing + isActive: JsonField = JsonMissing.of(), + @JsonProperty("last_name") + @ExcludeMissing + lastName: JsonField = JsonMissing.of(), + @JsonProperty("manager") + @ExcludeMissing + manager: JsonField = JsonMissing.of(), + @JsonProperty("middle_name") + @ExcludeMissing + middleName: JsonField = JsonMissing.of(), + ) : this( + id, + department, + firstName, + isActive, + lastName, + manager, + middleName, + mutableMapOf(), + ) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun department(): Optional = department.getOptional("department") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun isActive(): Optional = isActive.getOptional("is_active") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun manager(): Optional = manager.getOptional("manager") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [department]. + * + * Unlike [department], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("department") @ExcludeMissing fun _department(): JsonField = department + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName + /** + * Returns the raw JSON value of [isActive]. + * + * Unlike [isActive], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("is_active") @ExcludeMissing fun _isActive(): JsonField = isActive + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName + /** + * Returns the raw JSON value of [manager]. + * + * Unlike [manager], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("manager") @ExcludeMissing fun _manager(): JsonField = manager + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("middle_name") @ExcludeMissing fun _middleName(): JsonField = middleName + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Individuals = apply { - if (validated) { - return@apply - } - - id() - department() - firstName() - isActive() - lastName() - manager().ifPresent { it.validate() } - middleName() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [Individuals]. + */ @JvmStatic fun builder() = Builder() } @@ -1920,35 +3176,77 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun department(department: Boolean) = department(JsonField.of(department)) + /** + * Sets [Builder.department] to an arbitrary JSON value. + * + * You should usually call [Builder.department] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun department(department: JsonField) = apply { this.department = department } fun firstName(firstName: Boolean) = firstName(JsonField.of(firstName)) + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun firstName(firstName: JsonField) = apply { this.firstName = firstName } fun isActive(isActive: Boolean) = isActive(JsonField.of(isActive)) + /** + * Sets [Builder.isActive] to an arbitrary JSON value. + * + * You should usually call [Builder.isActive] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun isActive(isActive: JsonField) = apply { this.isActive = isActive } fun lastName(lastName: Boolean) = lastName(JsonField.of(lastName)) + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun lastName(lastName: JsonField) = apply { this.lastName = lastName } fun manager(manager: Manager) = manager(JsonField.of(manager)) + /** + * Sets [Builder.manager] to an arbitrary JSON value. + * + * You should usually call [Builder.manager] with a well-typed [Manager] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun manager(manager: JsonField) = apply { this.manager = manager } @@ -1956,6 +3254,13 @@ private constructor( fun middleName(middleName: Boolean) = middleName(JsonField.of(middleName)) + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun middleName(middleName: JsonField) = apply { this.middleName = middleName } @@ -1982,6 +3287,12 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Individuals]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Individuals = Individuals( id, @@ -1991,46 +3302,96 @@ private constructor( lastName, manager, middleName, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Individuals = apply { + if (validated) { + return@apply + } + + id() + department() + firstName() + isActive() + lastName() + manager().ifPresent { it.validate() } + middleName() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (department.asKnown().isPresent) 1 else 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (if (isActive.asKnown().isPresent) 1 else 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (manager.asKnown().getOrNull()?.validity() ?: 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + class Manager - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val id: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - + @JsonCreator + private constructor( + @JsonProperty("id") + @ExcludeMissing + id: JsonField = JsonMissing.of() + ) : this(id, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = - additionalProperties - - private var validated: Boolean = false - - fun validate(): Manager = apply { - if (validated) { - return@apply - } - - id() - validated = true - } + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [Manager]. + */ @JvmStatic fun builder() = Builder() } @@ -2050,6 +3411,13 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun additionalProperties( @@ -2075,10 +3443,44 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Manager]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Manager = - Manager(id, additionalProperties.toImmutable()) + Manager(id, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Manager = apply { + if (validated) { + return@apply + } + + id() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (id.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2115,55 +3517,72 @@ private constructor( "Individuals{id=$id, department=$department, firstName=$firstName, isActive=$isActive, lastName=$lastName, manager=$manager, middleName=$middleName, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Paging - @JsonCreator private constructor( - @JsonProperty("count") - @ExcludeMissing - private val count: JsonField = JsonMissing.of(), - @JsonProperty("offset") - @ExcludeMissing - private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val count: JsonField, + private val offset: JsonField, + private val additionalProperties: MutableMap, ) { - fun count(): Optional = - Optional.ofNullable(count.getNullable("count")) - - fun offset(): Optional = - Optional.ofNullable(offset.getNullable("offset")) - + @JsonCreator + private constructor( + @JsonProperty("count") + @ExcludeMissing + count: JsonField = JsonMissing.of(), + @JsonProperty("offset") + @ExcludeMissing + offset: JsonField = JsonMissing.of(), + ) : this(count, offset, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun count(): Optional = count.getOptional("count") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun offset(): Optional = offset.getOptional("offset") + + /** + * Returns the raw JSON value of [count]. + * + * Unlike [count], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("count") @ExcludeMissing fun _count(): JsonField = count + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Paging = apply { - if (validated) { - return@apply - } - - count() - offset() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Paging]. + */ @JvmStatic fun builder() = Builder() } @@ -2184,10 +3603,24 @@ private constructor( fun count(count: Boolean) = count(JsonField.of(count)) + /** + * Sets [Builder.count] to an arbitrary JSON value. + * + * You should usually call [Builder.count] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun count(count: JsonField) = apply { this.count = count } fun offset(offset: Boolean) = offset(JsonField.of(offset)) + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun offset(offset: JsonField) = apply { this.offset = offset } fun additionalProperties(additionalProperties: Map) = @@ -2212,10 +3645,47 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Paging]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Paging = - Paging(count, offset, additionalProperties.toImmutable()) + Paging(count, offset, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Paging = apply { + if (validated) { + return@apply + } + + count() + offset() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (count.asKnown().isPresent) 1 else 0) + + (if (offset.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2252,213 +3722,391 @@ private constructor( "SupportedDirectoryFields{individuals=$individuals, paging=$paging, additionalProperties=$additionalProperties}" } - @NoAutoDetect class SupportedEmploymentFields - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("class_code") - @ExcludeMissing - private val classCode: JsonField = JsonMissing.of(), - @JsonProperty("custom_fields") - @ExcludeMissing - private val customFields: JsonField = JsonMissing.of(), - @JsonProperty("department") - @ExcludeMissing - private val department: JsonField = JsonMissing.of(), - @JsonProperty("employment") - @ExcludeMissing - private val employment: JsonField = JsonMissing.of(), - @JsonProperty("employment_status") - @ExcludeMissing - private val employmentStatus: JsonField = JsonMissing.of(), - @JsonProperty("end_date") - @ExcludeMissing - private val endDate: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("income") - @ExcludeMissing - private val income: JsonField = JsonMissing.of(), - @JsonProperty("income_history") - @ExcludeMissing - private val incomeHistory: JsonField = JsonMissing.of(), - @JsonProperty("is_active") - @ExcludeMissing - private val isActive: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), - @JsonProperty("location") - @ExcludeMissing - private val location: JsonField = JsonMissing.of(), - @JsonProperty("manager") - @ExcludeMissing - private val manager: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), - @JsonProperty("start_date") - @ExcludeMissing - private val startDate: JsonField = JsonMissing.of(), - @JsonProperty("title") - @ExcludeMissing - private val title: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val classCode: JsonField, + private val customFields: JsonField, + private val department: JsonField, + private val employment: JsonField, + private val employmentStatus: JsonField, + private val endDate: JsonField, + private val firstName: JsonField, + private val income: JsonField, + private val incomeHistory: JsonField, + private val isActive: JsonField, + private val lastName: JsonField, + private val location: JsonField, + private val manager: JsonField, + private val middleName: JsonField, + private val startDate: JsonField, + private val title: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") + @ExcludeMissing + id: JsonField = JsonMissing.of(), + @JsonProperty("class_code") + @ExcludeMissing + classCode: JsonField = JsonMissing.of(), + @JsonProperty("custom_fields") + @ExcludeMissing + customFields: JsonField = JsonMissing.of(), + @JsonProperty("department") + @ExcludeMissing + department: JsonField = JsonMissing.of(), + @JsonProperty("employment") + @ExcludeMissing + employment: JsonField = JsonMissing.of(), + @JsonProperty("employment_status") + @ExcludeMissing + employmentStatus: JsonField = JsonMissing.of(), + @JsonProperty("end_date") + @ExcludeMissing + endDate: JsonField = JsonMissing.of(), + @JsonProperty("first_name") + @ExcludeMissing + firstName: JsonField = JsonMissing.of(), + @JsonProperty("income") + @ExcludeMissing + income: JsonField = JsonMissing.of(), + @JsonProperty("income_history") + @ExcludeMissing + incomeHistory: JsonField = JsonMissing.of(), + @JsonProperty("is_active") + @ExcludeMissing + isActive: JsonField = JsonMissing.of(), + @JsonProperty("last_name") + @ExcludeMissing + lastName: JsonField = JsonMissing.of(), + @JsonProperty("location") + @ExcludeMissing + location: JsonField = JsonMissing.of(), + @JsonProperty("manager") + @ExcludeMissing + manager: JsonField = JsonMissing.of(), + @JsonProperty("middle_name") + @ExcludeMissing + middleName: JsonField = JsonMissing.of(), + @JsonProperty("start_date") + @ExcludeMissing + startDate: JsonField = JsonMissing.of(), + @JsonProperty("title") + @ExcludeMissing + title: JsonField = JsonMissing.of(), + ) : this( + id, + classCode, + customFields, + department, + employment, + employmentStatus, + endDate, + firstName, + income, + incomeHistory, + isActive, + lastName, + location, + manager, + middleName, + startDate, + title, + mutableMapOf(), + ) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") - fun classCode(): Optional = - Optional.ofNullable(classCode.getNullable("class_code")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun classCode(): Optional = classCode.getOptional("class_code") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun customFields(): Optional = - Optional.ofNullable(customFields.getNullable("custom_fields")) + customFields.getOptional("custom_fields") - fun department(): Optional = - Optional.ofNullable(department.getNullable("department")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun department(): Optional = department.getOptional("department") - fun employment(): Optional = - Optional.ofNullable(employment.getNullable("employment")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun employment(): Optional = employment.getOptional("employment") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun employmentStatus(): Optional = - Optional.ofNullable(employmentStatus.getNullable("employment_status")) + employmentStatus.getOptional("employment_status") - fun endDate(): Optional = - Optional.ofNullable(endDate.getNullable("end_date")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun endDate(): Optional = endDate.getOptional("end_date") - fun firstName(): Optional = - Optional.ofNullable(firstName.getNullable("first_name")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") - fun income(): Optional = - Optional.ofNullable(income.getNullable("income")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun income(): Optional = income.getOptional("income") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun incomeHistory(): Optional = - Optional.ofNullable(incomeHistory.getNullable("income_history")) + incomeHistory.getOptional("income_history") - fun isActive(): Optional = - Optional.ofNullable(isActive.getNullable("is_active")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun isActive(): Optional = isActive.getOptional("is_active") - fun lastName(): Optional = - Optional.ofNullable(lastName.getNullable("last_name")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") - fun location(): Optional = - Optional.ofNullable(location.getNullable("location")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun location(): Optional = location.getOptional("location") - fun manager(): Optional = - Optional.ofNullable(manager.getNullable("manager")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun manager(): Optional = manager.getOptional("manager") - fun middleName(): Optional = - Optional.ofNullable(middleName.getNullable("middle_name")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") - fun startDate(): Optional = - Optional.ofNullable(startDate.getNullable("start_date")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun startDate(): Optional = startDate.getOptional("start_date") - fun title(): Optional = Optional.ofNullable(title.getNullable("title")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun title(): Optional = title.getOptional("title") + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [classCode]. + * + * Unlike [classCode], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("class_code") @ExcludeMissing fun _classCode(): JsonField = classCode + /** + * Returns the raw JSON value of [customFields]. + * + * Unlike [customFields], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("custom_fields") @ExcludeMissing fun _customFields(): JsonField = customFields + /** + * Returns the raw JSON value of [department]. + * + * Unlike [department], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("department") @ExcludeMissing fun _department(): JsonField = department + /** + * Returns the raw JSON value of [employment]. + * + * Unlike [employment], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("employment") @ExcludeMissing fun _employment(): JsonField = employment + /** + * Returns the raw JSON value of [employmentStatus]. + * + * Unlike [employmentStatus], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("employment_status") @ExcludeMissing fun _employmentStatus(): JsonField = employmentStatus + /** + * Returns the raw JSON value of [endDate]. + * + * Unlike [endDate], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("end_date") @ExcludeMissing fun _endDate(): JsonField = endDate + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName + /** + * Returns the raw JSON value of [income]. + * + * Unlike [income], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("income") @ExcludeMissing fun _income(): JsonField = income + /** + * Returns the raw JSON value of [incomeHistory]. + * + * Unlike [incomeHistory], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("income_history") @ExcludeMissing fun _incomeHistory(): JsonField = incomeHistory + /** + * Returns the raw JSON value of [isActive]. + * + * Unlike [isActive], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("is_active") @ExcludeMissing fun _isActive(): JsonField = isActive + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName + /** + * Returns the raw JSON value of [location]. + * + * Unlike [location], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("location") @ExcludeMissing fun _location(): JsonField = location + /** + * Returns the raw JSON value of [manager]. + * + * Unlike [manager], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("manager") @ExcludeMissing fun _manager(): JsonField = manager + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("middle_name") @ExcludeMissing fun _middleName(): JsonField = middleName + /** + * Returns the raw JSON value of [startDate]. + * + * Unlike [startDate], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("start_date") @ExcludeMissing fun _startDate(): JsonField = startDate + /** + * Returns the raw JSON value of [title]. + * + * Unlike [title], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("title") @ExcludeMissing fun _title(): JsonField = title + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedEmploymentFields = apply { - if (validated) { - return@apply - } - - id() - classCode() - customFields() - department().ifPresent { it.validate() } - employment().ifPresent { it.validate() } - employmentStatus() - endDate() - firstName() - income().ifPresent { it.validate() } - incomeHistory() - isActive() - lastName() - location().ifPresent { it.validate() } - manager().ifPresent { it.validate() } - middleName() - startDate() - title() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedEmploymentFields]. + */ @JvmStatic fun builder() = Builder() } @@ -2511,10 +4159,24 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun classCode(classCode: Boolean) = classCode(JsonField.of(classCode)) + /** + * Sets [Builder.classCode] to an arbitrary JSON value. + * + * You should usually call [Builder.classCode] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun classCode(classCode: JsonField) = apply { this.classCode = classCode } @@ -2522,6 +4184,13 @@ private constructor( fun customFields(customFields: Boolean) = customFields(JsonField.of(customFields)) + /** + * Sets [Builder.customFields] to an arbitrary JSON value. + * + * You should usually call [Builder.customFields] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun customFields(customFields: JsonField) = apply { this.customFields = customFields } @@ -2529,6 +4198,13 @@ private constructor( fun department(department: Department) = department(JsonField.of(department)) + /** + * Sets [Builder.department] to an arbitrary JSON value. + * + * You should usually call [Builder.department] with a well-typed + * [Department] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun department(department: JsonField) = apply { this.department = department } @@ -2536,6 +4212,13 @@ private constructor( fun employment(employment: Employment) = employment(JsonField.of(employment)) + /** + * Sets [Builder.employment] to an arbitrary JSON value. + * + * You should usually call [Builder.employment] with a well-typed + * [Employment] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun employment(employment: JsonField) = apply { this.employment = employment } @@ -2543,67 +4226,151 @@ private constructor( fun employmentStatus(employmentStatus: Boolean) = employmentStatus(JsonField.of(employmentStatus)) + /** + * Sets [Builder.employmentStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.employmentStatus] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun employmentStatus(employmentStatus: JsonField) = apply { this.employmentStatus = employmentStatus } fun endDate(endDate: Boolean) = endDate(JsonField.of(endDate)) + /** + * Sets [Builder.endDate] to an arbitrary JSON value. + * + * You should usually call [Builder.endDate] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun endDate(endDate: JsonField) = apply { this.endDate = endDate } fun firstName(firstName: Boolean) = firstName(JsonField.of(firstName)) + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun firstName(firstName: JsonField) = apply { this.firstName = firstName } fun income(income: Income) = income(JsonField.of(income)) + /** + * Sets [Builder.income] to an arbitrary JSON value. + * + * You should usually call [Builder.income] with a well-typed [Income] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun income(income: JsonField) = apply { this.income = income } fun incomeHistory(incomeHistory: Boolean) = incomeHistory(JsonField.of(incomeHistory)) + /** + * Sets [Builder.incomeHistory] to an arbitrary JSON value. + * + * You should usually call [Builder.incomeHistory] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun incomeHistory(incomeHistory: JsonField) = apply { this.incomeHistory = incomeHistory } fun isActive(isActive: Boolean) = isActive(JsonField.of(isActive)) + /** + * Sets [Builder.isActive] to an arbitrary JSON value. + * + * You should usually call [Builder.isActive] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun isActive(isActive: JsonField) = apply { this.isActive = isActive } fun lastName(lastName: Boolean) = lastName(JsonField.of(lastName)) + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun lastName(lastName: JsonField) = apply { this.lastName = lastName } fun location(location: Location) = location(JsonField.of(location)) + /** + * Sets [Builder.location] to an arbitrary JSON value. + * + * You should usually call [Builder.location] with a well-typed [Location] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun location(location: JsonField) = apply { this.location = location } fun manager(manager: Manager) = manager(JsonField.of(manager)) + /** + * Sets [Builder.manager] to an arbitrary JSON value. + * + * You should usually call [Builder.manager] with a well-typed [Manager] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun manager(manager: JsonField) = apply { this.manager = manager } fun middleName(middleName: Boolean) = middleName(JsonField.of(middleName)) + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun middleName(middleName: JsonField) = apply { this.middleName = middleName } fun startDate(startDate: Boolean) = startDate(JsonField.of(startDate)) + /** + * Sets [Builder.startDate] to an arbitrary JSON value. + * + * You should usually call [Builder.startDate] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun startDate(startDate: JsonField) = apply { this.startDate = startDate } fun title(title: Boolean) = title(JsonField.of(title)) + /** + * Sets [Builder.title] to an arbitrary JSON value. + * + * You should usually call [Builder.title] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun title(title: JsonField) = apply { this.title = title } fun additionalProperties(additionalProperties: Map) = @@ -2628,6 +4395,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedEmploymentFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedEmploymentFields = SupportedEmploymentFields( id, @@ -2647,46 +4419,116 @@ private constructor( middleName, startDate, title, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect - class Department - @JsonCreator - private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), - ) { + private var validated: Boolean = false - fun name(): Optional = - Optional.ofNullable(name.getNullable("name")) + fun validate(): SupportedEmploymentFields = apply { + if (validated) { + return@apply + } - @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + id() + classCode() + customFields() + department().ifPresent { it.validate() } + employment().ifPresent { it.validate() } + employmentStatus() + endDate() + firstName() + income().ifPresent { it.validate() } + incomeHistory() + isActive() + lastName() + location().ifPresent { it.validate() } + manager().ifPresent { it.validate() } + middleName() + startDate() + title() + validated = true + } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } - private var validated: Boolean = false + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (classCode.asKnown().isPresent) 1 else 0) + + (if (customFields.asKnown().isPresent) 1 else 0) + + (department.asKnown().getOrNull()?.validity() ?: 0) + + (employment.asKnown().getOrNull()?.validity() ?: 0) + + (if (employmentStatus.asKnown().isPresent) 1 else 0) + + (if (endDate.asKnown().isPresent) 1 else 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (income.asKnown().getOrNull()?.validity() ?: 0) + + (if (incomeHistory.asKnown().isPresent) 1 else 0) + + (if (isActive.asKnown().isPresent) 1 else 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (location.asKnown().getOrNull()?.validity() ?: 0) + + (manager.asKnown().getOrNull()?.validity() ?: 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + + (if (startDate.asKnown().isPresent) 1 else 0) + + (if (title.asKnown().isPresent) 1 else 0) - fun validate(): Department = apply { - if (validated) { - return@apply - } + class Department + private constructor( + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { - name() - validated = true + @JsonCreator + private constructor( + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [Department]. + */ @JvmStatic fun builder() = Builder() } @@ -2706,6 +4548,13 @@ private constructor( fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = @@ -2730,10 +4579,44 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Department]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Department = - Department(name, additionalProperties.toImmutable()) + Department(name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Department = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2752,53 +4635,71 @@ private constructor( "Department{name=$name, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Employment - @JsonCreator private constructor( - @JsonProperty("subtype") - @ExcludeMissing - private val subtype: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val subtype: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun subtype(): Optional = - Optional.ofNullable(subtype.getNullable("subtype")) - - fun type(): Optional = - Optional.ofNullable(type.getNullable("type")) - + @JsonCreator + private constructor( + @JsonProperty("subtype") + @ExcludeMissing + subtype: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(subtype, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun subtype(): Optional = subtype.getOptional("subtype") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [subtype]. + * + * Unlike [subtype], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Employment = apply { - if (validated) { - return@apply - } - - subtype() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [Employment]. + */ @JvmStatic fun builder() = Builder() } @@ -2820,12 +4721,26 @@ private constructor( fun subtype(subtype: Boolean) = subtype(JsonField.of(subtype)) + /** + * Sets [Builder.subtype] to an arbitrary JSON value. + * + * You should usually call [Builder.subtype] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun subtype(subtype: JsonField) = apply { this.subtype = subtype } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = @@ -2850,10 +4765,47 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Employment]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Employment = - Employment(subtype, type, additionalProperties.toImmutable()) + Employment(subtype, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Employment = apply { + if (validated) { + return@apply + } + + subtype() + type() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (subtype.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2872,64 +4824,90 @@ private constructor( "Employment{subtype=$subtype, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Income - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("unit") - @ExcludeMissing - private val unit: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val amount: JsonField, + private val currency: JsonField, + private val unit: JsonField, + private val additionalProperties: MutableMap, ) { - fun amount(): Optional = - Optional.ofNullable(amount.getNullable("amount")) - - fun currency(): Optional = - Optional.ofNullable(currency.getNullable("currency")) - - fun unit(): Optional = - Optional.ofNullable(unit.getNullable("unit")) - + @JsonCreator + private constructor( + @JsonProperty("amount") + @ExcludeMissing + amount: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("unit") + @ExcludeMissing + unit: JsonField = JsonMissing.of(), + ) : this(amount, currency, unit, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun unit(): Optional = unit.getOptional("unit") + + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency + /** + * Returns the raw JSON value of [unit]. + * + * Unlike [unit], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("unit") @ExcludeMissing fun _unit(): JsonField = unit + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Income = apply { - if (validated) { - return@apply - } - - amount() - currency() - unit() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Income]. + */ @JvmStatic fun builder() = Builder() } @@ -2952,16 +4930,37 @@ private constructor( fun amount(amount: Boolean) = amount(JsonField.of(amount)) + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun currency(currency: Boolean) = currency(JsonField.of(currency)) + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } fun unit(unit: Boolean) = unit(JsonField.of(unit)) + /** + * Sets [Builder.unit] to an arbitrary JSON value. + * + * You should usually call [Builder.unit] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun unit(unit: JsonField) = apply { this.unit = unit } fun additionalProperties(additionalProperties: Map) = @@ -2986,10 +4985,49 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Income]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Income = - Income(amount, currency, unit, additionalProperties.toImmutable()) + Income(amount, currency, unit, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Income = apply { + if (validated) { + return@apply + } + + amount() + currency() + unit() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (unit.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3008,97 +5046,150 @@ private constructor( "Income{amount=$amount, currency=$currency, unit=$unit, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Location - @JsonCreator private constructor( - @JsonProperty("city") - @ExcludeMissing - private val city: JsonField = JsonMissing.of(), - @JsonProperty("country") - @ExcludeMissing - private val country: JsonField = JsonMissing.of(), - @JsonProperty("line1") - @ExcludeMissing - private val line1: JsonField = JsonMissing.of(), - @JsonProperty("line2") - @ExcludeMissing - private val line2: JsonField = JsonMissing.of(), - @JsonProperty("postal_code") - @ExcludeMissing - private val postalCode: JsonField = JsonMissing.of(), - @JsonProperty("state") - @ExcludeMissing - private val state: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val city: JsonField, + private val country: JsonField, + private val line1: JsonField, + private val line2: JsonField, + private val postalCode: JsonField, + private val state: JsonField, + private val additionalProperties: MutableMap, ) { - fun city(): Optional = - Optional.ofNullable(city.getNullable("city")) - - fun country(): Optional = - Optional.ofNullable(country.getNullable("country")) - - fun line1(): Optional = - Optional.ofNullable(line1.getNullable("line1")) - - fun line2(): Optional = - Optional.ofNullable(line2.getNullable("line2")) - - fun postalCode(): Optional = - Optional.ofNullable(postalCode.getNullable("postal_code")) - - fun state(): Optional = - Optional.ofNullable(state.getNullable("state")) - + @JsonCreator + private constructor( + @JsonProperty("city") + @ExcludeMissing + city: JsonField = JsonMissing.of(), + @JsonProperty("country") + @ExcludeMissing + country: JsonField = JsonMissing.of(), + @JsonProperty("line1") + @ExcludeMissing + line1: JsonField = JsonMissing.of(), + @JsonProperty("line2") + @ExcludeMissing + line2: JsonField = JsonMissing.of(), + @JsonProperty("postal_code") + @ExcludeMissing + postalCode: JsonField = JsonMissing.of(), + @JsonProperty("state") + @ExcludeMissing + state: JsonField = JsonMissing.of(), + ) : this(city, country, line1, line2, postalCode, state, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun city(): Optional = city.getOptional("city") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun country(): Optional = country.getOptional("country") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun line1(): Optional = line1.getOptional("line1") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun line2(): Optional = line2.getOptional("line2") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun postalCode(): Optional = postalCode.getOptional("postal_code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun state(): Optional = state.getOptional("state") + + /** + * Returns the raw JSON value of [city]. + * + * Unlike [city], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("city") @ExcludeMissing fun _city(): JsonField = city + /** + * Returns the raw JSON value of [country]. + * + * Unlike [country], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("country") @ExcludeMissing fun _country(): JsonField = country + /** + * Returns the raw JSON value of [line1]. + * + * Unlike [line1], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("line1") @ExcludeMissing fun _line1(): JsonField = line1 + /** + * Returns the raw JSON value of [line2]. + * + * Unlike [line2], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("line2") @ExcludeMissing fun _line2(): JsonField = line2 + /** + * Returns the raw JSON value of [postalCode]. + * + * Unlike [postalCode], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("postal_code") @ExcludeMissing fun _postalCode(): JsonField = postalCode + /** + * Returns the raw JSON value of [state]. + * + * Unlike [state], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("state") @ExcludeMissing fun _state(): JsonField = state + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Location = apply { - if (validated) { - return@apply - } - - city() - country() - line1() - line2() - postalCode() - state() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Location]. + */ @JvmStatic fun builder() = Builder() } @@ -3127,31 +5218,73 @@ private constructor( fun city(city: Boolean) = city(JsonField.of(city)) + /** + * Sets [Builder.city] to an arbitrary JSON value. + * + * You should usually call [Builder.city] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun city(city: JsonField) = apply { this.city = city } fun country(country: Boolean) = country(JsonField.of(country)) + /** + * Sets [Builder.country] to an arbitrary JSON value. + * + * You should usually call [Builder.country] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun country(country: JsonField) = apply { this.country = country } fun line1(line1: Boolean) = line1(JsonField.of(line1)) + /** + * Sets [Builder.line1] to an arbitrary JSON value. + * + * You should usually call [Builder.line1] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun line1(line1: JsonField) = apply { this.line1 = line1 } fun line2(line2: Boolean) = line2(JsonField.of(line2)) + /** + * Sets [Builder.line2] to an arbitrary JSON value. + * + * You should usually call [Builder.line2] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun line2(line2: JsonField) = apply { this.line2 = line2 } fun postalCode(postalCode: Boolean) = postalCode(JsonField.of(postalCode)) + /** + * Sets [Builder.postalCode] to an arbitrary JSON value. + * + * You should usually call [Builder.postalCode] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun postalCode(postalCode: JsonField) = apply { this.postalCode = postalCode } fun state(state: Boolean) = state(JsonField.of(state)) + /** + * Sets [Builder.state] to an arbitrary JSON value. + * + * You should usually call [Builder.state] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun state(state: JsonField) = apply { this.state = state } fun additionalProperties(additionalProperties: Map) = @@ -3176,6 +5309,12 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Location]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Location = Location( city, @@ -3184,10 +5323,49 @@ private constructor( line2, postalCode, state, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Location = apply { + if (validated) { + return@apply + } + + city() + country() + line1() + line2() + postalCode() + state() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (city.asKnown().isPresent) 1 else 0) + + (if (country.asKnown().isPresent) 1 else 0) + + (if (line1.asKnown().isPresent) 1 else 0) + + (if (line2.asKnown().isPresent) 1 else 0) + + (if (postalCode.asKnown().isPresent) 1 else 0) + + (if (state.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3206,41 +5384,50 @@ private constructor( "Location{city=$city, country=$country, line1=$line1, line2=$line2, postalCode=$postalCode, state=$state, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Manager - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val id: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - + @JsonCreator + private constructor( + @JsonProperty("id") + @ExcludeMissing + id: JsonField = JsonMissing.of() + ) : this(id, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Manager = apply { - if (validated) { - return@apply - } - - id() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Manager]. + */ @JvmStatic fun builder() = Builder() } @@ -3259,6 +5446,13 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun additionalProperties(additionalProperties: Map) = @@ -3283,9 +5477,43 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Manager = Manager(id, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Manager]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): Manager = Manager(id, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Manager = apply { + if (validated) { + return@apply + } + + id() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (id.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3311,177 +5539,316 @@ private constructor( return /* spotless:off */ other is SupportedEmploymentFields && id == other.id && classCode == other.classCode && customFields == other.customFields && department == other.department && employment == other.employment && employmentStatus == other.employmentStatus && endDate == other.endDate && firstName == other.firstName && income == other.income && incomeHistory == other.incomeHistory && isActive == other.isActive && lastName == other.lastName && location == other.location && manager == other.manager && middleName == other.middleName && startDate == other.startDate && title == other.title && additionalProperties == other.additionalProperties /* spotless:on */ } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, classCode, customFields, department, employment, employmentStatus, endDate, firstName, income, incomeHistory, isActive, lastName, location, manager, middleName, startDate, title, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "SupportedEmploymentFields{id=$id, classCode=$classCode, customFields=$customFields, department=$department, employment=$employment, employmentStatus=$employmentStatus, endDate=$endDate, firstName=$firstName, income=$income, incomeHistory=$incomeHistory, isActive=$isActive, lastName=$lastName, location=$location, manager=$manager, middleName=$middleName, startDate=$startDate, title=$title, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class SupportedIndividualFields - @JsonCreator - private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("dob") - @ExcludeMissing - private val dob: JsonField = JsonMissing.of(), - @JsonProperty("emails") - @ExcludeMissing - private val emails: JsonField = JsonMissing.of(), - @JsonProperty("encrypted_ssn") - @ExcludeMissing - private val encryptedSsn: JsonField = JsonMissing.of(), - @JsonProperty("ethnicity") - @ExcludeMissing - private val ethnicity: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("gender") - @ExcludeMissing - private val gender: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), - @JsonProperty("phone_numbers") - @ExcludeMissing - private val phoneNumbers: JsonField = JsonMissing.of(), - @JsonProperty("preferred_name") - @ExcludeMissing - private val preferredName: JsonField = JsonMissing.of(), - @JsonProperty("residence") - @ExcludeMissing - private val residence: JsonField = JsonMissing.of(), - @JsonProperty("ssn") - @ExcludeMissing - private val ssn: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(id, classCode, customFields, department, employment, employmentStatus, endDate, firstName, income, incomeHistory, isActive, lastName, location, manager, middleName, startDate, title, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SupportedEmploymentFields{id=$id, classCode=$classCode, customFields=$customFields, department=$department, employment=$employment, employmentStatus=$employmentStatus, endDate=$endDate, firstName=$firstName, income=$income, incomeHistory=$incomeHistory, isActive=$isActive, lastName=$lastName, location=$location, manager=$manager, middleName=$middleName, startDate=$startDate, title=$title, additionalProperties=$additionalProperties}" + } + + class SupportedIndividualFields + private constructor( + private val id: JsonField, + private val dob: JsonField, + private val emails: JsonField, + private val encryptedSsn: JsonField, + private val ethnicity: JsonField, + private val firstName: JsonField, + private val gender: JsonField, + private val lastName: JsonField, + private val middleName: JsonField, + private val phoneNumbers: JsonField, + private val preferredName: JsonField, + private val residence: JsonField, + private val ssn: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") + @ExcludeMissing + id: JsonField = JsonMissing.of(), + @JsonProperty("dob") + @ExcludeMissing + dob: JsonField = JsonMissing.of(), + @JsonProperty("emails") + @ExcludeMissing + emails: JsonField = JsonMissing.of(), + @JsonProperty("encrypted_ssn") + @ExcludeMissing + encryptedSsn: JsonField = JsonMissing.of(), + @JsonProperty("ethnicity") + @ExcludeMissing + ethnicity: JsonField = JsonMissing.of(), + @JsonProperty("first_name") + @ExcludeMissing + firstName: JsonField = JsonMissing.of(), + @JsonProperty("gender") + @ExcludeMissing + gender: JsonField = JsonMissing.of(), + @JsonProperty("last_name") + @ExcludeMissing + lastName: JsonField = JsonMissing.of(), + @JsonProperty("middle_name") + @ExcludeMissing + middleName: JsonField = JsonMissing.of(), + @JsonProperty("phone_numbers") + @ExcludeMissing + phoneNumbers: JsonField = JsonMissing.of(), + @JsonProperty("preferred_name") + @ExcludeMissing + preferredName: JsonField = JsonMissing.of(), + @JsonProperty("residence") + @ExcludeMissing + residence: JsonField = JsonMissing.of(), + @JsonProperty("ssn") + @ExcludeMissing + ssn: JsonField = JsonMissing.of(), + ) : this( + id, + dob, + emails, + encryptedSsn, + ethnicity, + firstName, + gender, + lastName, + middleName, + phoneNumbers, + preferredName, + residence, + ssn, + mutableMapOf(), + ) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") - fun dob(): Optional = Optional.ofNullable(dob.getNullable("dob")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun dob(): Optional = dob.getOptional("dob") - fun emails(): Optional = - Optional.ofNullable(emails.getNullable("emails")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun emails(): Optional = emails.getOptional("emails") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun encryptedSsn(): Optional = - Optional.ofNullable(encryptedSsn.getNullable("encrypted_ssn")) + encryptedSsn.getOptional("encrypted_ssn") - fun ethnicity(): Optional = - Optional.ofNullable(ethnicity.getNullable("ethnicity")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun ethnicity(): Optional = ethnicity.getOptional("ethnicity") - fun firstName(): Optional = - Optional.ofNullable(firstName.getNullable("first_name")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") - fun gender(): Optional = - Optional.ofNullable(gender.getNullable("gender")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun gender(): Optional = gender.getOptional("gender") - fun lastName(): Optional = - Optional.ofNullable(lastName.getNullable("last_name")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") - fun middleName(): Optional = - Optional.ofNullable(middleName.getNullable("middle_name")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun phoneNumbers(): Optional = - Optional.ofNullable(phoneNumbers.getNullable("phone_numbers")) + phoneNumbers.getOptional("phone_numbers") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun preferredName(): Optional = - Optional.ofNullable(preferredName.getNullable("preferred_name")) + preferredName.getOptional("preferred_name") - fun residence(): Optional = - Optional.ofNullable(residence.getNullable("residence")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun residence(): Optional = residence.getOptional("residence") - fun ssn(): Optional = Optional.ofNullable(ssn.getNullable("ssn")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun ssn(): Optional = ssn.getOptional("ssn") + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [dob]. + * + * Unlike [dob], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("dob") @ExcludeMissing fun _dob(): JsonField = dob + /** + * Returns the raw JSON value of [emails]. + * + * Unlike [emails], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("emails") @ExcludeMissing fun _emails(): JsonField = emails + /** + * Returns the raw JSON value of [encryptedSsn]. + * + * Unlike [encryptedSsn], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("encrypted_ssn") @ExcludeMissing fun _encryptedSsn(): JsonField = encryptedSsn + /** + * Returns the raw JSON value of [ethnicity]. + * + * Unlike [ethnicity], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("ethnicity") @ExcludeMissing fun _ethnicity(): JsonField = ethnicity + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName + /** + * Returns the raw JSON value of [gender]. + * + * Unlike [gender], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("gender") @ExcludeMissing fun _gender(): JsonField = gender + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("middle_name") @ExcludeMissing fun _middleName(): JsonField = middleName + /** + * Returns the raw JSON value of [phoneNumbers]. + * + * Unlike [phoneNumbers], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("phone_numbers") @ExcludeMissing fun _phoneNumbers(): JsonField = phoneNumbers + /** + * Returns the raw JSON value of [preferredName]. + * + * Unlike [preferredName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("preferred_name") @ExcludeMissing fun _preferredName(): JsonField = preferredName + /** + * Returns the raw JSON value of [residence]. + * + * Unlike [residence], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("residence") @ExcludeMissing fun _residence(): JsonField = residence + /** + * Returns the raw JSON value of [ssn]. + * + * Unlike [ssn], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("ssn") @ExcludeMissing fun _ssn(): JsonField = ssn + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedIndividualFields = apply { - if (validated) { - return@apply - } - - id() - dob() - emails().ifPresent { it.validate() } - encryptedSsn() - ethnicity() - firstName() - gender() - lastName() - middleName() - phoneNumbers().ifPresent { it.validate() } - preferredName() - residence().ifPresent { it.validate() } - ssn() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedIndividualFields]. + */ @JvmStatic fun builder() = Builder() } @@ -3526,47 +5893,110 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun dob(dob: Boolean) = dob(JsonField.of(dob)) + /** + * Sets [Builder.dob] to an arbitrary JSON value. + * + * You should usually call [Builder.dob] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun dob(dob: JsonField) = apply { this.dob = dob } fun emails(emails: Emails) = emails(JsonField.of(emails)) + /** + * Sets [Builder.emails] to an arbitrary JSON value. + * + * You should usually call [Builder.emails] with a well-typed [Emails] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun emails(emails: JsonField) = apply { this.emails = emails } fun encryptedSsn(encryptedSsn: Boolean) = encryptedSsn(JsonField.of(encryptedSsn)) + /** + * Sets [Builder.encryptedSsn] to an arbitrary JSON value. + * + * You should usually call [Builder.encryptedSsn] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun encryptedSsn(encryptedSsn: JsonField) = apply { this.encryptedSsn = encryptedSsn } fun ethnicity(ethnicity: Boolean) = ethnicity(JsonField.of(ethnicity)) + /** + * Sets [Builder.ethnicity] to an arbitrary JSON value. + * + * You should usually call [Builder.ethnicity] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun ethnicity(ethnicity: JsonField) = apply { this.ethnicity = ethnicity } fun firstName(firstName: Boolean) = firstName(JsonField.of(firstName)) + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun firstName(firstName: JsonField) = apply { this.firstName = firstName } fun gender(gender: Boolean) = gender(JsonField.of(gender)) + /** + * Sets [Builder.gender] to an arbitrary JSON value. + * + * You should usually call [Builder.gender] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun gender(gender: JsonField) = apply { this.gender = gender } fun lastName(lastName: Boolean) = lastName(JsonField.of(lastName)) + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun lastName(lastName: JsonField) = apply { this.lastName = lastName } fun middleName(middleName: Boolean) = middleName(JsonField.of(middleName)) + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun middleName(middleName: JsonField) = apply { this.middleName = middleName } @@ -3574,6 +6004,13 @@ private constructor( fun phoneNumbers(phoneNumbers: PhoneNumbers) = phoneNumbers(JsonField.of(phoneNumbers)) + /** + * Sets [Builder.phoneNumbers] to an arbitrary JSON value. + * + * You should usually call [Builder.phoneNumbers] with a well-typed + * [PhoneNumbers] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun phoneNumbers(phoneNumbers: JsonField) = apply { this.phoneNumbers = phoneNumbers } @@ -3581,18 +6018,39 @@ private constructor( fun preferredName(preferredName: Boolean) = preferredName(JsonField.of(preferredName)) + /** + * Sets [Builder.preferredName] to an arbitrary JSON value. + * + * You should usually call [Builder.preferredName] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun preferredName(preferredName: JsonField) = apply { this.preferredName = preferredName } fun residence(residence: Residence) = residence(JsonField.of(residence)) + /** + * Sets [Builder.residence] to an arbitrary JSON value. + * + * You should usually call [Builder.residence] with a well-typed [Residence] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun residence(residence: JsonField) = apply { this.residence = residence } fun ssn(ssn: Boolean) = ssn(JsonField.of(ssn)) + /** + * Sets [Builder.ssn] to an arbitrary JSON value. + * + * You should usually call [Builder.ssn] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun ssn(ssn: JsonField) = apply { this.ssn = ssn } fun additionalProperties(additionalProperties: Map) = @@ -3617,6 +6075,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedIndividualFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedIndividualFields = SupportedIndividualFields( id, @@ -3632,55 +6095,125 @@ private constructor( preferredName, residence, ssn, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): SupportedIndividualFields = apply { + if (validated) { + return@apply + } + + id() + dob() + emails().ifPresent { it.validate() } + encryptedSsn() + ethnicity() + firstName() + gender() + lastName() + middleName() + phoneNumbers().ifPresent { it.validate() } + preferredName() + residence().ifPresent { it.validate() } + ssn() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (dob.asKnown().isPresent) 1 else 0) + + (emails.asKnown().getOrNull()?.validity() ?: 0) + + (if (encryptedSsn.asKnown().isPresent) 1 else 0) + + (if (ethnicity.asKnown().isPresent) 1 else 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (if (gender.asKnown().isPresent) 1 else 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + + (phoneNumbers.asKnown().getOrNull()?.validity() ?: 0) + + (if (preferredName.asKnown().isPresent) 1 else 0) + + (residence.asKnown().getOrNull()?.validity() ?: 0) + + (if (ssn.asKnown().isPresent) 1 else 0) + class Emails - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun data(): Optional = - Optional.ofNullable(data.getNullable("data")) - - fun type(): Optional = - Optional.ofNullable(type.getNullable("type")) - + @JsonCreator + private constructor( + @JsonProperty("data") + @ExcludeMissing + data: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Emails = apply { - if (validated) { - return@apply - } - - data() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Emails]. + */ @JvmStatic fun builder() = Builder() } @@ -3701,10 +6234,24 @@ private constructor( fun data(data: Boolean) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = @@ -3729,10 +6276,47 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Emails]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Emails = - Emails(data, type, additionalProperties.toImmutable()) + Emails(data, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Emails = apply { + if (validated) { + return@apply + } + + data() + type() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3751,51 +6335,69 @@ private constructor( "Emails{data=$data, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class PhoneNumbers - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun data(): Optional = - Optional.ofNullable(data.getNullable("data")) - - fun type(): Optional = - Optional.ofNullable(type.getNullable("type")) - + @JsonCreator + private constructor( + @JsonProperty("data") + @ExcludeMissing + data: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PhoneNumbers = apply { - if (validated) { - return@apply - } - - data() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [PhoneNumbers]. + */ @JvmStatic fun builder() = Builder() } @@ -3817,10 +6419,24 @@ private constructor( fun data(data: Boolean) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = @@ -3845,119 +6461,210 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PhoneNumbers]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): PhoneNumbers = - PhoneNumbers(data, type, additionalProperties.toImmutable()) + PhoneNumbers(data, type, additionalProperties.toMutableMap()) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + private var validated: Boolean = false + + fun validate(): PhoneNumbers = apply { + if (validated) { + return@apply } - return /* spotless:off */ other is PhoneNumbers && data == other.data && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ + data() + type() + validated = true } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(data, type, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "PhoneNumbers{data=$data, type=$type, additionalProperties=$additionalProperties}" - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } - @NoAutoDetect - class Residence - @JsonCreator - private constructor( - @JsonProperty("city") - @ExcludeMissing - private val city: JsonField = JsonMissing.of(), - @JsonProperty("country") - @ExcludeMissing - private val country: JsonField = JsonMissing.of(), - @JsonProperty("line1") - @ExcludeMissing - private val line1: JsonField = JsonMissing.of(), - @JsonProperty("line2") - @ExcludeMissing - private val line2: JsonField = JsonMissing.of(), - @JsonProperty("postal_code") - @ExcludeMissing - private val postalCode: JsonField = JsonMissing.of(), - @JsonProperty("state") - @ExcludeMissing - private val state: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), - ) { + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) - fun city(): Optional = - Optional.ofNullable(city.getNullable("city")) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun country(): Optional = - Optional.ofNullable(country.getNullable("country")) + return /* spotless:off */ other is PhoneNumbers && data == other.data && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ + } - fun line1(): Optional = - Optional.ofNullable(line1.getNullable("line1")) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(data, type, additionalProperties) } + /* spotless:on */ - fun line2(): Optional = - Optional.ofNullable(line2.getNullable("line2")) + override fun hashCode(): Int = hashCode - fun postalCode(): Optional = - Optional.ofNullable(postalCode.getNullable("postal_code")) + override fun toString() = + "PhoneNumbers{data=$data, type=$type, additionalProperties=$additionalProperties}" + } - fun state(): Optional = - Optional.ofNullable(state.getNullable("state")) + class Residence + private constructor( + private val city: JsonField, + private val country: JsonField, + private val line1: JsonField, + private val line2: JsonField, + private val postalCode: JsonField, + private val state: JsonField, + private val additionalProperties: MutableMap, + ) { + @JsonCreator + private constructor( + @JsonProperty("city") + @ExcludeMissing + city: JsonField = JsonMissing.of(), + @JsonProperty("country") + @ExcludeMissing + country: JsonField = JsonMissing.of(), + @JsonProperty("line1") + @ExcludeMissing + line1: JsonField = JsonMissing.of(), + @JsonProperty("line2") + @ExcludeMissing + line2: JsonField = JsonMissing.of(), + @JsonProperty("postal_code") + @ExcludeMissing + postalCode: JsonField = JsonMissing.of(), + @JsonProperty("state") + @ExcludeMissing + state: JsonField = JsonMissing.of(), + ) : this(city, country, line1, line2, postalCode, state, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun city(): Optional = city.getOptional("city") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun country(): Optional = country.getOptional("country") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun line1(): Optional = line1.getOptional("line1") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun line2(): Optional = line2.getOptional("line2") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun postalCode(): Optional = postalCode.getOptional("postal_code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun state(): Optional = state.getOptional("state") + + /** + * Returns the raw JSON value of [city]. + * + * Unlike [city], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("city") @ExcludeMissing fun _city(): JsonField = city + /** + * Returns the raw JSON value of [country]. + * + * Unlike [country], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("country") @ExcludeMissing fun _country(): JsonField = country + /** + * Returns the raw JSON value of [line1]. + * + * Unlike [line1], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("line1") @ExcludeMissing fun _line1(): JsonField = line1 + /** + * Returns the raw JSON value of [line2]. + * + * Unlike [line2], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("line2") @ExcludeMissing fun _line2(): JsonField = line2 + /** + * Returns the raw JSON value of [postalCode]. + * + * Unlike [postalCode], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("postal_code") @ExcludeMissing fun _postalCode(): JsonField = postalCode + /** + * Returns the raw JSON value of [state]. + * + * Unlike [state], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("state") @ExcludeMissing fun _state(): JsonField = state + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Residence = apply { - if (validated) { - return@apply - } - - city() - country() - line1() - line2() - postalCode() - state() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [Residence]. + */ @JvmStatic fun builder() = Builder() } @@ -3986,31 +6693,73 @@ private constructor( fun city(city: Boolean) = city(JsonField.of(city)) + /** + * Sets [Builder.city] to an arbitrary JSON value. + * + * You should usually call [Builder.city] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun city(city: JsonField) = apply { this.city = city } fun country(country: Boolean) = country(JsonField.of(country)) + /** + * Sets [Builder.country] to an arbitrary JSON value. + * + * You should usually call [Builder.country] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun country(country: JsonField) = apply { this.country = country } fun line1(line1: Boolean) = line1(JsonField.of(line1)) + /** + * Sets [Builder.line1] to an arbitrary JSON value. + * + * You should usually call [Builder.line1] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun line1(line1: JsonField) = apply { this.line1 = line1 } fun line2(line2: Boolean) = line2(JsonField.of(line2)) + /** + * Sets [Builder.line2] to an arbitrary JSON value. + * + * You should usually call [Builder.line2] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun line2(line2: JsonField) = apply { this.line2 = line2 } fun postalCode(postalCode: Boolean) = postalCode(JsonField.of(postalCode)) + /** + * Sets [Builder.postalCode] to an arbitrary JSON value. + * + * You should usually call [Builder.postalCode] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun postalCode(postalCode: JsonField) = apply { this.postalCode = postalCode } fun state(state: Boolean) = state(JsonField.of(state)) + /** + * Sets [Builder.state] to an arbitrary JSON value. + * + * You should usually call [Builder.state] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun state(state: JsonField) = apply { this.state = state } fun additionalProperties(additionalProperties: Map) = @@ -4035,6 +6784,12 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Residence]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Residence = Residence( city, @@ -4043,10 +6798,49 @@ private constructor( line2, postalCode, state, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Residence = apply { + if (validated) { + return@apply + } + + city() + country() + line1() + line2() + postalCode() + state() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (city.asKnown().isPresent) 1 else 0) + + (if (country.asKnown().isPresent) 1 else 0) + + (if (line1.asKnown().isPresent) 1 else 0) + + (if (line2.asKnown().isPresent) 1 else 0) + + (if (postalCode.asKnown().isPresent) 1 else 0) + + (if (state.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4083,70 +6877,111 @@ private constructor( "SupportedIndividualFields{id=$id, dob=$dob, emails=$emails, encryptedSsn=$encryptedSsn, ethnicity=$ethnicity, firstName=$firstName, gender=$gender, lastName=$lastName, middleName=$middleName, phoneNumbers=$phoneNumbers, preferredName=$preferredName, residence=$residence, ssn=$ssn, additionalProperties=$additionalProperties}" } - @NoAutoDetect class SupportedPayGroupFields - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("individual_ids") - @ExcludeMissing - private val individualIds: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("pay_frequencies") - @ExcludeMissing - private val payFrequencies: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val individualIds: JsonField, + private val name: JsonField, + private val payFrequencies: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") + @ExcludeMissing + id: JsonField = JsonMissing.of(), + @JsonProperty("individual_ids") + @ExcludeMissing + individualIds: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("pay_frequencies") + @ExcludeMissing + payFrequencies: JsonField = JsonMissing.of(), + ) : this(id, individualIds, name, payFrequencies, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun individualIds(): Optional = - Optional.ofNullable(individualIds.getNullable("individual_ids")) + individualIds.getOptional("individual_ids") - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun payFrequencies(): Optional = - Optional.ofNullable(payFrequencies.getNullable("pay_frequencies")) + payFrequencies.getOptional("pay_frequencies") + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [individualIds]. + * + * Unlike [individualIds], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("individual_ids") @ExcludeMissing fun _individualIds(): JsonField = individualIds + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + /** + * Returns the raw JSON value of [payFrequencies]. + * + * Unlike [payFrequencies], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("pay_frequencies") @ExcludeMissing fun _payFrequencies(): JsonField = payFrequencies + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedPayGroupFields = apply { - if (validated) { - return@apply - } - - id() - individualIds() - name() - payFrequencies() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedPayGroupFields]. + */ @JvmStatic fun builder() = Builder() } @@ -4173,22 +7008,50 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun individualIds(individualIds: Boolean) = individualIds(JsonField.of(individualIds)) + /** + * Sets [Builder.individualIds] to an arbitrary JSON value. + * + * You should usually call [Builder.individualIds] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun individualIds(individualIds: JsonField) = apply { this.individualIds = individualIds } fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun payFrequencies(payFrequencies: Boolean) = payFrequencies(JsonField.of(payFrequencies)) + /** + * Sets [Builder.payFrequencies] to an arbitrary JSON value. + * + * You should usually call [Builder.payFrequencies] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun payFrequencies(payFrequencies: JsonField) = apply { this.payFrequencies = payFrequencies } @@ -4215,16 +7078,56 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedPayGroupFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedPayGroupFields = SupportedPayGroupFields( id, individualIds, name, payFrequencies, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): SupportedPayGroupFields = apply { + if (validated) { + return@apply + } + + id() + individualIds() + name() + payFrequencies() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (individualIds.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (payFrequencies.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4243,54 +7146,74 @@ private constructor( "SupportedPayGroupFields{id=$id, individualIds=$individualIds, name=$name, payFrequencies=$payFrequencies, additionalProperties=$additionalProperties}" } - @NoAutoDetect class SupportedPayStatementFields - @JsonCreator private constructor( - @JsonProperty("paging") - @ExcludeMissing - private val paging: JsonField = JsonMissing.of(), - @JsonProperty("pay_statements") - @ExcludeMissing - private val payStatements: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val paging: JsonField, + private val payStatements: JsonField, + private val additionalProperties: MutableMap, ) { - fun paging(): Optional = - Optional.ofNullable(paging.getNullable("paging")) + @JsonCreator + private constructor( + @JsonProperty("paging") + @ExcludeMissing + paging: JsonField = JsonMissing.of(), + @JsonProperty("pay_statements") + @ExcludeMissing + payStatements: JsonField = JsonMissing.of(), + ) : this(paging, payStatements, mutableMapOf()) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun paging(): Optional = paging.getOptional("paging") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun payStatements(): Optional = - Optional.ofNullable(payStatements.getNullable("pay_statements")) + payStatements.getOptional("pay_statements") + /** + * Returns the raw JSON value of [paging]. + * + * Unlike [paging], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("paging") @ExcludeMissing fun _paging(): JsonField = paging + /** + * Returns the raw JSON value of [payStatements]. + * + * Unlike [payStatements], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("pay_statements") @ExcludeMissing fun _payStatements(): JsonField = payStatements + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedPayStatementFields = apply { - if (validated) { - return@apply - } - - paging().ifPresent { it.validate() } - payStatements().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedPayStatementFields]. + */ @JvmStatic fun builder() = Builder() } @@ -4314,11 +7237,25 @@ private constructor( fun paging(paging: Paging) = paging(JsonField.of(paging)) + /** + * Sets [Builder.paging] to an arbitrary JSON value. + * + * You should usually call [Builder.paging] with a well-typed [Paging] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun paging(paging: JsonField) = apply { this.paging = paging } fun payStatements(payStatements: PayStatements) = payStatements(JsonField.of(payStatements)) + /** + * Sets [Builder.payStatements] to an arbitrary JSON value. + * + * You should usually call [Builder.payStatements] with a well-typed + * [PayStatements] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun payStatements(payStatements: JsonField) = apply { this.payStatements = payStatements } @@ -4345,61 +7282,124 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedPayStatementFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedPayStatementFields = SupportedPayStatementFields( paging, payStatements, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): SupportedPayStatementFields = apply { + if (validated) { + return@apply + } + + paging().ifPresent { it.validate() } + payStatements().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (paging.asKnown().getOrNull()?.validity() ?: 0) + + (payStatements.asKnown().getOrNull()?.validity() ?: 0) + class Paging - @JsonCreator private constructor( - @JsonProperty("count") - @ExcludeMissing - private val count: JsonField = JsonMissing.of(), - @JsonProperty("offset") - @ExcludeMissing - private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val count: JsonField, + private val offset: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("count") + @ExcludeMissing + count: JsonField = JsonMissing.of(), + @JsonProperty("offset") + @ExcludeMissing + offset: JsonField = JsonMissing.of(), + ) : this(count, offset, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ fun count(): Boolean = count.getRequired("count") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type or is unexpectedly missing or null (e.g. if the server responded + * with an unexpected value). + */ fun offset(): Boolean = offset.getRequired("offset") + /** + * Returns the raw JSON value of [count]. + * + * Unlike [count], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("count") @ExcludeMissing fun _count(): JsonField = count + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Paging = apply { - if (validated) { - return@apply - } - - count() - offset() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Paging]. + * + * The following fields are required: + * ```java + * .count() + * .offset() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -4420,10 +7420,24 @@ private constructor( fun count(count: Boolean) = count(JsonField.of(count)) + /** + * Sets [Builder.count] to an arbitrary JSON value. + * + * You should usually call [Builder.count] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun count(count: JsonField) = apply { this.count = count } fun offset(offset: Boolean) = offset(JsonField.of(offset)) + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun offset(offset: JsonField) = apply { this.offset = offset } fun additionalProperties(additionalProperties: Map) = @@ -4448,175 +7462,321 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Paging]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .count() + * .offset() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Paging = Paging( checkRequired("count", count), checkRequired("offset", offset), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + private var validated: Boolean = false + + fun validate(): Paging = apply { + if (validated) { + return@apply } - return /* spotless:off */ other is Paging && count == other.count && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ + count() + offset() + validated = true } - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(count, offset, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Paging{count=$count, offset=$offset, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class PayStatements - @JsonCreator - private constructor( - @JsonProperty("earnings") - @ExcludeMissing - private val earnings: JsonField = JsonMissing.of(), - @JsonProperty("employee_deductions") - @ExcludeMissing - private val employeeDeductions: JsonField = - JsonMissing.of(), - @JsonProperty("employer_contributions") - @ExcludeMissing - private val employerContributions: JsonField = - JsonMissing.of(), - @JsonProperty("gross_pay") - @ExcludeMissing - private val grossPay: JsonField = JsonMissing.of(), - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonProperty("net_pay") - @ExcludeMissing - private val netPay: JsonField = JsonMissing.of(), - @JsonProperty("payment_method") - @ExcludeMissing - private val paymentMethod: JsonField = JsonMissing.of(), - @JsonProperty("taxes") - @ExcludeMissing - private val taxes: JsonField = JsonMissing.of(), - @JsonProperty("total_hours") - @ExcludeMissing - private val totalHours: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), - ) { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } - fun earnings(): Optional = - Optional.ofNullable(earnings.getNullable("earnings")) + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (count.asKnown().isPresent) 1 else 0) + + (if (offset.asKnown().isPresent) 1 else 0) - fun employeeDeductions(): Optional = - Optional.ofNullable( - employeeDeductions.getNullable("employee_deductions") - ) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun employerContributions(): Optional = - Optional.ofNullable( - employerContributions.getNullable("employer_contributions") - ) + return /* spotless:off */ other is Paging && count == other.count && offset == other.offset && additionalProperties == other.additionalProperties /* spotless:on */ + } - fun grossPay(): Optional = - Optional.ofNullable(grossPay.getNullable("gross_pay")) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(count, offset, additionalProperties) } + /* spotless:on */ - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) + override fun hashCode(): Int = hashCode - fun netPay(): Optional = - Optional.ofNullable(netPay.getNullable("net_pay")) + override fun toString() = + "Paging{count=$count, offset=$offset, additionalProperties=$additionalProperties}" + } - fun paymentMethod(): Optional = - Optional.ofNullable(paymentMethod.getNullable("payment_method")) + class PayStatements + private constructor( + private val earnings: JsonField, + private val employeeDeductions: JsonField, + private val employerContributions: JsonField, + private val grossPay: JsonField, + private val individualId: JsonField, + private val netPay: JsonField, + private val paymentMethod: JsonField, + private val taxes: JsonField, + private val totalHours: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, + ) { - fun taxes(): Optional = - Optional.ofNullable(taxes.getNullable("taxes")) + @JsonCreator + private constructor( + @JsonProperty("earnings") + @ExcludeMissing + earnings: JsonField = JsonMissing.of(), + @JsonProperty("employee_deductions") + @ExcludeMissing + employeeDeductions: JsonField = JsonMissing.of(), + @JsonProperty("employer_contributions") + @ExcludeMissing + employerContributions: JsonField = + JsonMissing.of(), + @JsonProperty("gross_pay") + @ExcludeMissing + grossPay: JsonField = JsonMissing.of(), + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of(), + @JsonProperty("net_pay") + @ExcludeMissing + netPay: JsonField = JsonMissing.of(), + @JsonProperty("payment_method") + @ExcludeMissing + paymentMethod: JsonField = JsonMissing.of(), + @JsonProperty("taxes") + @ExcludeMissing + taxes: JsonField = JsonMissing.of(), + @JsonProperty("total_hours") + @ExcludeMissing + totalHours: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this( + earnings, + employeeDeductions, + employerContributions, + grossPay, + individualId, + netPay, + paymentMethod, + taxes, + totalHours, + type, + mutableMapOf(), + ) - fun totalHours(): Optional = - Optional.ofNullable(totalHours.getNullable("total_hours")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun earnings(): Optional = earnings.getOptional("earnings") - fun type(): Optional = - Optional.ofNullable(type.getNullable("type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun employeeDeductions(): Optional = + employeeDeductions.getOptional("employee_deductions") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun employerContributions(): Optional = + employerContributions.getOptional("employer_contributions") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun grossPay(): Optional = grossPay.getOptional("gross_pay") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun individualId(): Optional = + individualId.getOptional("individual_id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun netPay(): Optional = netPay.getOptional("net_pay") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun paymentMethod(): Optional = + paymentMethod.getOptional("payment_method") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun taxes(): Optional = taxes.getOptional("taxes") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun totalHours(): Optional = totalHours.getOptional("total_hours") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [earnings]. + * + * Unlike [earnings], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("earnings") @ExcludeMissing fun _earnings(): JsonField = earnings + /** + * Returns the raw JSON value of [employeeDeductions]. + * + * Unlike [employeeDeductions], this method doesn't throw if the JSON field + * has an unexpected type. + */ @JsonProperty("employee_deductions") @ExcludeMissing fun _employeeDeductions(): JsonField = employeeDeductions + /** + * Returns the raw JSON value of [employerContributions]. + * + * Unlike [employerContributions], this method doesn't throw if the JSON + * field has an unexpected type. + */ @JsonProperty("employer_contributions") @ExcludeMissing fun _employerContributions(): JsonField = employerContributions + /** + * Returns the raw JSON value of [grossPay]. + * + * Unlike [grossPay], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("gross_pay") @ExcludeMissing fun _grossPay(): JsonField = grossPay + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + /** + * Returns the raw JSON value of [netPay]. + * + * Unlike [netPay], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("net_pay") @ExcludeMissing fun _netPay(): JsonField = netPay + /** + * Returns the raw JSON value of [paymentMethod]. + * + * Unlike [paymentMethod], this method doesn't throw if the JSON field has + * an unexpected type. + */ @JsonProperty("payment_method") @ExcludeMissing fun _paymentMethod(): JsonField = paymentMethod + /** + * Returns the raw JSON value of [taxes]. + * + * Unlike [taxes], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("taxes") @ExcludeMissing fun _taxes(): JsonField = taxes + /** + * Returns the raw JSON value of [totalHours]. + * + * Unlike [totalHours], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("total_hours") @ExcludeMissing fun _totalHours(): JsonField = totalHours + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PayStatements = apply { - if (validated) { - return@apply - } - - earnings().ifPresent { it.validate() } - employeeDeductions().ifPresent { it.validate() } - employerContributions().ifPresent { it.validate() } - grossPay() - individualId() - netPay() - paymentMethod() - taxes().ifPresent { it.validate() } - totalHours() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [PayStatements]. + */ @JvmStatic fun builder() = Builder() } @@ -4656,6 +7816,13 @@ private constructor( fun earnings(earnings: Earnings) = earnings(JsonField.of(earnings)) + /** + * Sets [Builder.earnings] to an arbitrary JSON value. + * + * You should usually call [Builder.earnings] with a well-typed + * [Earnings] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun earnings(earnings: JsonField) = apply { this.earnings = earnings } @@ -4663,6 +7830,14 @@ private constructor( fun employeeDeductions(employeeDeductions: EmployeeDeductions) = employeeDeductions(JsonField.of(employeeDeductions)) + /** + * Sets [Builder.employeeDeductions] to an arbitrary JSON value. + * + * You should usually call [Builder.employeeDeductions] with a + * well-typed [EmployeeDeductions] value instead. This method is + * primarily for setting the field to an undocumented or not yet + * supported value. + */ fun employeeDeductions( employeeDeductions: JsonField ) = apply { this.employeeDeductions = employeeDeductions } @@ -4671,12 +7846,27 @@ private constructor( employerContributions: EmployerContributions ) = employerContributions(JsonField.of(employerContributions)) + /** + * Sets [Builder.employerContributions] to an arbitrary JSON value. + * + * You should usually call [Builder.employerContributions] with a + * well-typed [EmployerContributions] value instead. This method is + * primarily for setting the field to an undocumented or not yet + * supported value. + */ fun employerContributions( employerContributions: JsonField ) = apply { this.employerContributions = employerContributions } fun grossPay(grossPay: Boolean) = grossPay(JsonField.of(grossPay)) + /** + * Sets [Builder.grossPay] to an arbitrary JSON value. + * + * You should usually call [Builder.grossPay] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun grossPay(grossPay: JsonField) = apply { this.grossPay = grossPay } @@ -4684,34 +7874,76 @@ private constructor( fun individualId(individualId: Boolean) = individualId(JsonField.of(individualId)) + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } fun netPay(netPay: Boolean) = netPay(JsonField.of(netPay)) + /** + * Sets [Builder.netPay] to an arbitrary JSON value. + * + * You should usually call [Builder.netPay] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun netPay(netPay: JsonField) = apply { this.netPay = netPay } fun paymentMethod(paymentMethod: Boolean) = paymentMethod(JsonField.of(paymentMethod)) + /** + * Sets [Builder.paymentMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.paymentMethod] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun paymentMethod(paymentMethod: JsonField) = apply { this.paymentMethod = paymentMethod } fun taxes(taxes: Taxes) = taxes(JsonField.of(taxes)) + /** + * Sets [Builder.taxes] to an arbitrary JSON value. + * + * You should usually call [Builder.taxes] with a well-typed [Taxes] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun taxes(taxes: JsonField) = apply { this.taxes = taxes } fun totalHours(totalHours: Boolean) = totalHours(JsonField.of(totalHours)) + /** + * Sets [Builder.totalHours] to an arbitrary JSON value. + * + * You should usually call [Builder.totalHours] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun totalHours(totalHours: JsonField) = apply { this.totalHours = totalHours } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = @@ -4736,6 +7968,12 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PayStatements]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): PayStatements = PayStatements( earnings, @@ -4748,82 +7986,164 @@ private constructor( taxes, totalHours, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect - class Earnings - @JsonCreator - private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), - ) { + private var validated: Boolean = false + + fun validate(): PayStatements = apply { + if (validated) { + return@apply + } - fun amount(): Optional = - Optional.ofNullable(amount.getNullable("amount")) + earnings().ifPresent { it.validate() } + employeeDeductions().ifPresent { it.validate() } + employerContributions().ifPresent { it.validate() } + grossPay() + individualId() + netPay() + paymentMethod() + taxes().ifPresent { it.validate() } + totalHours() + type() + validated = true + } - fun currency(): Optional = - Optional.ofNullable(currency.getNullable("currency")) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } - fun name(): Optional = - Optional.ofNullable(name.getNullable("name")) + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (earnings.asKnown().getOrNull()?.validity() ?: 0) + + (employeeDeductions.asKnown().getOrNull()?.validity() ?: 0) + + (employerContributions.asKnown().getOrNull()?.validity() ?: 0) + + (if (grossPay.asKnown().isPresent) 1 else 0) + + (if (individualId.asKnown().isPresent) 1 else 0) + + (if (netPay.asKnown().isPresent) 1 else 0) + + (if (paymentMethod.asKnown().isPresent) 1 else 0) + + (taxes.asKnown().getOrNull()?.validity() ?: 0) + + (if (totalHours.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) - fun type(): Optional = - Optional.ofNullable(type.getNullable("type")) + class Earnings + private constructor( + private val amount: JsonField, + private val currency: JsonField, + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, + ) { + @JsonCreator + private constructor( + @JsonProperty("amount") + @ExcludeMissing + amount: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(amount, currency, name, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = - additionalProperties - - private var validated: Boolean = false - - fun validate(): Earnings = apply { - if (validated) { - return@apply - } - - amount() - currency() - name() - type() - validated = true - } + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [Earnings]. + */ @JvmStatic fun builder() = Builder() } @@ -4849,22 +8169,50 @@ private constructor( fun amount(amount: Boolean) = amount(JsonField.of(amount)) + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun currency(currency: Boolean) = currency(JsonField.of(currency)) + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties( @@ -4890,16 +8238,57 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Earnings]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Earnings = Earnings( amount, currency, name, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Earnings = apply { + if (validated) { + return@apply + } + + amount() + currency() + name() + type() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4918,89 +8307,133 @@ private constructor( "Earnings{amount=$amount, currency=$currency, name=$name, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class EmployeeDeductions - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("pre_tax") - @ExcludeMissing - private val preTax: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val amount: JsonField, + private val currency: JsonField, + private val name: JsonField, + private val preTax: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun amount(): Optional = - Optional.ofNullable(amount.getNullable("amount")) - - fun currency(): Optional = - Optional.ofNullable(currency.getNullable("currency")) - - fun name(): Optional = - Optional.ofNullable(name.getNullable("name")) - - fun preTax(): Optional = - Optional.ofNullable(preTax.getNullable("pre_tax")) - - fun type(): Optional = - Optional.ofNullable(type.getNullable("type")) - + @JsonCreator + private constructor( + @JsonProperty("amount") + @ExcludeMissing + amount: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("pre_tax") + @ExcludeMissing + preTax: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(amount, currency, name, preTax, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun preTax(): Optional = preTax.getOptional("pre_tax") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + /** + * Returns the raw JSON value of [preTax]. + * + * Unlike [preTax], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("pre_tax") @ExcludeMissing fun _preTax(): JsonField = preTax + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = - additionalProperties - - private var validated: Boolean = false - - fun validate(): EmployeeDeductions = apply { - if (validated) { - return@apply - } - - amount() - currency() - name() - preTax() - type() - validated = true - } + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [EmployeeDeductions]. + */ @JvmStatic fun builder() = Builder() } @@ -5028,28 +8461,63 @@ private constructor( fun amount(amount: Boolean) = amount(JsonField.of(amount)) + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun currency(currency: Boolean) = currency(JsonField.of(currency)) + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun preTax(preTax: Boolean) = preTax(JsonField.of(preTax)) + /** + * Sets [Builder.preTax] to an arbitrary JSON value. + * + * You should usually call [Builder.preTax] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun preTax(preTax: JsonField) = apply { this.preTax = preTax } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties( @@ -5075,6 +8543,12 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [EmployeeDeductions]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): EmployeeDeductions = EmployeeDeductions( amount, @@ -5082,10 +8556,47 @@ private constructor( name, preTax, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): EmployeeDeductions = apply { + if (validated) { + return@apply + } + + amount() + currency() + name() + preTax() + type() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (preTax.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -5104,67 +8615,93 @@ private constructor( "EmployeeDeductions{amount=$amount, currency=$currency, name=$name, preTax=$preTax, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class EmployerContributions - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val amount: JsonField, + private val currency: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - fun amount(): Optional = - Optional.ofNullable(amount.getNullable("amount")) - - fun currency(): Optional = - Optional.ofNullable(currency.getNullable("currency")) - - fun name(): Optional = - Optional.ofNullable(name.getNullable("name")) - + @JsonCreator + private constructor( + @JsonProperty("amount") + @ExcludeMissing + amount: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + ) : this(amount, currency, name, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = - additionalProperties - - private var validated: Boolean = false - - fun validate(): EmployerContributions = apply { - if (validated) { - return@apply - } - - amount() - currency() - name() - validated = true - } + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [EmployerContributions]. + */ @JvmStatic fun builder() = Builder() } @@ -5190,18 +8727,39 @@ private constructor( fun amount(amount: Boolean) = amount(JsonField.of(amount)) + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun currency(currency: Boolean) = currency(JsonField.of(currency)) + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties( @@ -5227,15 +8785,54 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [EmployerContributions]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): EmployerContributions = EmployerContributions( amount, currency, name, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): EmployerContributions = apply { + if (validated) { + return@apply + } + + amount() + currency() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -5254,89 +8851,133 @@ private constructor( "EmployerContributions{amount=$amount, currency=$currency, name=$name, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Taxes - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("employer") - @ExcludeMissing - private val employer: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val amount: JsonField, + private val currency: JsonField, + private val employer: JsonField, + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun amount(): Optional = - Optional.ofNullable(amount.getNullable("amount")) - - fun currency(): Optional = - Optional.ofNullable(currency.getNullable("currency")) - - fun employer(): Optional = - Optional.ofNullable(employer.getNullable("employer")) - - fun name(): Optional = - Optional.ofNullable(name.getNullable("name")) - - fun type(): Optional = - Optional.ofNullable(type.getNullable("type")) - + @JsonCreator + private constructor( + @JsonProperty("amount") + @ExcludeMissing + amount: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("employer") + @ExcludeMissing + employer: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(amount, currency, employer, name, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun employer(): Optional = employer.getOptional("employer") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency + /** + * Returns the raw JSON value of [employer]. + * + * Unlike [employer], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("employer") @ExcludeMissing fun _employer(): JsonField = employer + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = - additionalProperties - - private var validated: Boolean = false - - fun validate(): Taxes = apply { - if (validated) { - return@apply - } - - amount() - currency() - employer() - name() - type() - validated = true - } + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [Taxes]. + */ @JvmStatic fun builder() = Builder() } @@ -5363,28 +9004,63 @@ private constructor( fun amount(amount: Boolean) = amount(JsonField.of(amount)) + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun currency(currency: Boolean) = currency(JsonField.of(currency)) + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } fun employer(employer: Boolean) = employer(JsonField.of(employer)) + /** + * Sets [Builder.employer] to an arbitrary JSON value. + * + * You should usually call [Builder.employer] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun employer(employer: JsonField) = apply { this.employer = employer } fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties( @@ -5410,6 +9086,12 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Taxes]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Taxes = Taxes( amount, @@ -5417,10 +9099,47 @@ private constructor( employer, name, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Taxes = apply { + if (validated) { + return@apply + } + + amount() + currency() + employer() + name() + type() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in + * this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (employer.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -5475,161 +9194,290 @@ private constructor( "SupportedPayStatementFields{paging=$paging, payStatements=$payStatements, additionalProperties=$additionalProperties}" } - @NoAutoDetect class SupportedPaymentFields - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("company_debit") - @ExcludeMissing - private val companyDebit: JsonField = JsonMissing.of(), - @JsonProperty("debit_date") - @ExcludeMissing - private val debitDate: JsonField = JsonMissing.of(), - @JsonProperty("employee_taxes") - @ExcludeMissing - private val employeeTaxes: JsonField = JsonMissing.of(), - @JsonProperty("employer_taxes") - @ExcludeMissing - private val employerTaxes: JsonField = JsonMissing.of(), - @JsonProperty("gross_pay") - @ExcludeMissing - private val grossPay: JsonField = JsonMissing.of(), - @JsonProperty("individual_ids") - @ExcludeMissing - private val individualIds: JsonField = JsonMissing.of(), - @JsonProperty("net_pay") - @ExcludeMissing - private val netPay: JsonField = JsonMissing.of(), - @JsonProperty("pay_date") - @ExcludeMissing - private val payDate: JsonField = JsonMissing.of(), - @JsonProperty("pay_frequencies") - @ExcludeMissing - private val payFrequencies: JsonField = JsonMissing.of(), - @JsonProperty("pay_group_ids") - @ExcludeMissing - private val payGroupIds: JsonField = JsonMissing.of(), - @JsonProperty("pay_period") - @ExcludeMissing - private val payPeriod: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val companyDebit: JsonField, + private val debitDate: JsonField, + private val employeeTaxes: JsonField, + private val employerTaxes: JsonField, + private val grossPay: JsonField, + private val individualIds: JsonField, + private val netPay: JsonField, + private val payDate: JsonField, + private val payFrequencies: JsonField, + private val payGroupIds: JsonField, + private val payPeriod: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") + @ExcludeMissing + id: JsonField = JsonMissing.of(), + @JsonProperty("company_debit") + @ExcludeMissing + companyDebit: JsonField = JsonMissing.of(), + @JsonProperty("debit_date") + @ExcludeMissing + debitDate: JsonField = JsonMissing.of(), + @JsonProperty("employee_taxes") + @ExcludeMissing + employeeTaxes: JsonField = JsonMissing.of(), + @JsonProperty("employer_taxes") + @ExcludeMissing + employerTaxes: JsonField = JsonMissing.of(), + @JsonProperty("gross_pay") + @ExcludeMissing + grossPay: JsonField = JsonMissing.of(), + @JsonProperty("individual_ids") + @ExcludeMissing + individualIds: JsonField = JsonMissing.of(), + @JsonProperty("net_pay") + @ExcludeMissing + netPay: JsonField = JsonMissing.of(), + @JsonProperty("pay_date") + @ExcludeMissing + payDate: JsonField = JsonMissing.of(), + @JsonProperty("pay_frequencies") + @ExcludeMissing + payFrequencies: JsonField = JsonMissing.of(), + @JsonProperty("pay_group_ids") + @ExcludeMissing + payGroupIds: JsonField = JsonMissing.of(), + @JsonProperty("pay_period") + @ExcludeMissing + payPeriod: JsonField = JsonMissing.of(), + ) : this( + id, + companyDebit, + debitDate, + employeeTaxes, + employerTaxes, + grossPay, + individualIds, + netPay, + payDate, + payFrequencies, + payGroupIds, + payPeriod, + mutableMapOf(), + ) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun companyDebit(): Optional = - Optional.ofNullable(companyDebit.getNullable("company_debit")) + companyDebit.getOptional("company_debit") - fun debitDate(): Optional = - Optional.ofNullable(debitDate.getNullable("debit_date")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun debitDate(): Optional = debitDate.getOptional("debit_date") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun employeeTaxes(): Optional = - Optional.ofNullable(employeeTaxes.getNullable("employee_taxes")) + employeeTaxes.getOptional("employee_taxes") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun employerTaxes(): Optional = - Optional.ofNullable(employerTaxes.getNullable("employer_taxes")) + employerTaxes.getOptional("employer_taxes") - fun grossPay(): Optional = - Optional.ofNullable(grossPay.getNullable("gross_pay")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun grossPay(): Optional = grossPay.getOptional("gross_pay") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun individualIds(): Optional = - Optional.ofNullable(individualIds.getNullable("individual_ids")) + individualIds.getOptional("individual_ids") - fun netPay(): Optional = - Optional.ofNullable(netPay.getNullable("net_pay")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun netPay(): Optional = netPay.getOptional("net_pay") - fun payDate(): Optional = - Optional.ofNullable(payDate.getNullable("pay_date")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun payDate(): Optional = payDate.getOptional("pay_date") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun payFrequencies(): Optional = - Optional.ofNullable(payFrequencies.getNullable("pay_frequencies")) + payFrequencies.getOptional("pay_frequencies") - fun payGroupIds(): Optional = - Optional.ofNullable(payGroupIds.getNullable("pay_group_ids")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun payGroupIds(): Optional = payGroupIds.getOptional("pay_group_ids") - fun payPeriod(): Optional = - Optional.ofNullable(payPeriod.getNullable("pay_period")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun payPeriod(): Optional = payPeriod.getOptional("pay_period") + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [companyDebit]. + * + * Unlike [companyDebit], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("company_debit") @ExcludeMissing fun _companyDebit(): JsonField = companyDebit + /** + * Returns the raw JSON value of [debitDate]. + * + * Unlike [debitDate], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("debit_date") @ExcludeMissing fun _debitDate(): JsonField = debitDate + /** + * Returns the raw JSON value of [employeeTaxes]. + * + * Unlike [employeeTaxes], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("employee_taxes") @ExcludeMissing fun _employeeTaxes(): JsonField = employeeTaxes + /** + * Returns the raw JSON value of [employerTaxes]. + * + * Unlike [employerTaxes], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("employer_taxes") @ExcludeMissing fun _employerTaxes(): JsonField = employerTaxes + /** + * Returns the raw JSON value of [grossPay]. + * + * Unlike [grossPay], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("gross_pay") @ExcludeMissing fun _grossPay(): JsonField = grossPay + /** + * Returns the raw JSON value of [individualIds]. + * + * Unlike [individualIds], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("individual_ids") @ExcludeMissing fun _individualIds(): JsonField = individualIds + /** + * Returns the raw JSON value of [netPay]. + * + * Unlike [netPay], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("net_pay") @ExcludeMissing fun _netPay(): JsonField = netPay + /** + * Returns the raw JSON value of [payDate]. + * + * Unlike [payDate], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("pay_date") @ExcludeMissing fun _payDate(): JsonField = payDate + /** + * Returns the raw JSON value of [payFrequencies]. + * + * Unlike [payFrequencies], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("pay_frequencies") @ExcludeMissing fun _payFrequencies(): JsonField = payFrequencies + /** + * Returns the raw JSON value of [payGroupIds]. + * + * Unlike [payGroupIds], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("pay_group_ids") @ExcludeMissing fun _payGroupIds(): JsonField = payGroupIds + /** + * Returns the raw JSON value of [payPeriod]. + * + * Unlike [payPeriod], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("pay_period") @ExcludeMissing fun _payPeriod(): JsonField = payPeriod + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedPaymentFields = apply { - if (validated) { - return@apply - } - - id() - companyDebit() - debitDate() - employeeTaxes() - employerTaxes() - grossPay() - individualIds() - netPay() - payDate() - payFrequencies() - payGroupIds() - payPeriod().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedPaymentFields]. + */ @JvmStatic fun builder() = Builder() } @@ -5671,17 +9519,38 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun companyDebit(companyDebit: Boolean) = companyDebit(JsonField.of(companyDebit)) + /** + * Sets [Builder.companyDebit] to an arbitrary JSON value. + * + * You should usually call [Builder.companyDebit] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun companyDebit(companyDebit: JsonField) = apply { this.companyDebit = companyDebit } fun debitDate(debitDate: Boolean) = debitDate(JsonField.of(debitDate)) + /** + * Sets [Builder.debitDate] to an arbitrary JSON value. + * + * You should usually call [Builder.debitDate] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun debitDate(debitDate: JsonField) = apply { this.debitDate = debitDate } @@ -5689,6 +9558,13 @@ private constructor( fun employeeTaxes(employeeTaxes: Boolean) = employeeTaxes(JsonField.of(employeeTaxes)) + /** + * Sets [Builder.employeeTaxes] to an arbitrary JSON value. + * + * You should usually call [Builder.employeeTaxes] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun employeeTaxes(employeeTaxes: JsonField) = apply { this.employeeTaxes = employeeTaxes } @@ -5696,12 +9572,26 @@ private constructor( fun employerTaxes(employerTaxes: Boolean) = employerTaxes(JsonField.of(employerTaxes)) + /** + * Sets [Builder.employerTaxes] to an arbitrary JSON value. + * + * You should usually call [Builder.employerTaxes] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun employerTaxes(employerTaxes: JsonField) = apply { this.employerTaxes = employerTaxes } fun grossPay(grossPay: Boolean) = grossPay(JsonField.of(grossPay)) + /** + * Sets [Builder.grossPay] to an arbitrary JSON value. + * + * You should usually call [Builder.grossPay] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun grossPay(grossPay: JsonField) = apply { this.grossPay = grossPay } @@ -5709,21 +9599,49 @@ private constructor( fun individualIds(individualIds: Boolean) = individualIds(JsonField.of(individualIds)) + /** + * Sets [Builder.individualIds] to an arbitrary JSON value. + * + * You should usually call [Builder.individualIds] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun individualIds(individualIds: JsonField) = apply { this.individualIds = individualIds } fun netPay(netPay: Boolean) = netPay(JsonField.of(netPay)) + /** + * Sets [Builder.netPay] to an arbitrary JSON value. + * + * You should usually call [Builder.netPay] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun netPay(netPay: JsonField) = apply { this.netPay = netPay } fun payDate(payDate: Boolean) = payDate(JsonField.of(payDate)) + /** + * Sets [Builder.payDate] to an arbitrary JSON value. + * + * You should usually call [Builder.payDate] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun payDate(payDate: JsonField) = apply { this.payDate = payDate } fun payFrequencies(payFrequencies: Boolean) = payFrequencies(JsonField.of(payFrequencies)) + /** + * Sets [Builder.payFrequencies] to an arbitrary JSON value. + * + * You should usually call [Builder.payFrequencies] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun payFrequencies(payFrequencies: JsonField) = apply { this.payFrequencies = payFrequencies } @@ -5731,12 +9649,26 @@ private constructor( fun payGroupIds(payGroupIds: Boolean) = payGroupIds(JsonField.of(payGroupIds)) + /** + * Sets [Builder.payGroupIds] to an arbitrary JSON value. + * + * You should usually call [Builder.payGroupIds] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun payGroupIds(payGroupIds: JsonField) = apply { this.payGroupIds = payGroupIds } fun payPeriod(payPeriod: PayPeriod) = payPeriod(JsonField.of(payPeriod)) + /** + * Sets [Builder.payPeriod] to an arbitrary JSON value. + * + * You should usually call [Builder.payPeriod] with a well-typed [PayPeriod] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun payPeriod(payPeriod: JsonField) = apply { this.payPeriod = payPeriod } @@ -5763,6 +9695,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedPaymentFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedPaymentFields = SupportedPaymentFields( id, @@ -5777,59 +9714,128 @@ private constructor( payFrequencies, payGroupIds, payPeriod, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): SupportedPaymentFields = apply { + if (validated) { + return@apply + } + + id() + companyDebit() + debitDate() + employeeTaxes() + employerTaxes() + grossPay() + individualIds() + netPay() + payDate() + payFrequencies() + payGroupIds() + payPeriod().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (companyDebit.asKnown().isPresent) 1 else 0) + + (if (debitDate.asKnown().isPresent) 1 else 0) + + (if (employeeTaxes.asKnown().isPresent) 1 else 0) + + (if (employerTaxes.asKnown().isPresent) 1 else 0) + + (if (grossPay.asKnown().isPresent) 1 else 0) + + (if (individualIds.asKnown().isPresent) 1 else 0) + + (if (netPay.asKnown().isPresent) 1 else 0) + + (if (payDate.asKnown().isPresent) 1 else 0) + + (if (payFrequencies.asKnown().isPresent) 1 else 0) + + (if (payGroupIds.asKnown().isPresent) 1 else 0) + + (payPeriod.asKnown().getOrNull()?.validity() ?: 0) + class PayPeriod - @JsonCreator private constructor( - @JsonProperty("end_date") - @ExcludeMissing - private val endDate: JsonField = JsonMissing.of(), - @JsonProperty("start_date") - @ExcludeMissing - private val startDate: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val endDate: JsonField, + private val startDate: JsonField, + private val additionalProperties: MutableMap, ) { - fun endDate(): Optional = - Optional.ofNullable(endDate.getNullable("end_date")) - - fun startDate(): Optional = - Optional.ofNullable(startDate.getNullable("start_date")) - + @JsonCreator + private constructor( + @JsonProperty("end_date") + @ExcludeMissing + endDate: JsonField = JsonMissing.of(), + @JsonProperty("start_date") + @ExcludeMissing + startDate: JsonField = JsonMissing.of(), + ) : this(endDate, startDate, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun endDate(): Optional = endDate.getOptional("end_date") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun startDate(): Optional = startDate.getOptional("start_date") + + /** + * Returns the raw JSON value of [endDate]. + * + * Unlike [endDate], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("end_date") @ExcludeMissing fun _endDate(): JsonField = endDate + /** + * Returns the raw JSON value of [startDate]. + * + * Unlike [startDate], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("start_date") @ExcludeMissing fun _startDate(): JsonField = startDate + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PayPeriod = apply { - if (validated) { - return@apply - } - - endDate() - startDate() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [PayPeriod]. + */ @JvmStatic fun builder() = Builder() } @@ -5850,12 +9856,26 @@ private constructor( fun endDate(endDate: Boolean) = endDate(JsonField.of(endDate)) + /** + * Sets [Builder.endDate] to an arbitrary JSON value. + * + * You should usually call [Builder.endDate] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun endDate(endDate: JsonField) = apply { this.endDate = endDate } fun startDate(startDate: Boolean) = startDate(JsonField.of(startDate)) + /** + * Sets [Builder.startDate] to an arbitrary JSON value. + * + * You should usually call [Builder.startDate] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun startDate(startDate: JsonField) = apply { this.startDate = startDate } @@ -5882,10 +9902,47 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PayPeriod]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): PayPeriod = - PayPeriod(endDate, startDate, additionalProperties.toImmutable()) + PayPeriod(endDate, startDate, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): PayPeriod = apply { + if (validated) { + return@apply + } + + endDate() + startDate() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (endDate.asKnown().isPresent) 1 else 0) + + (if (startDate.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -6049,6 +10106,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -6178,6 +10262,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EventType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountUpdateResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountUpdateResponse.kt index ef5ca08a..cbbb1e2d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountUpdateResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AccountUpdateResponse.kt @@ -11,107 +11,176 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class AccountUpdateResponse -@JsonCreator private constructor( - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("authentication_type") - @ExcludeMissing - private val authenticationType: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("products") - @ExcludeMissing - private val products: JsonField> = JsonMissing.of(), - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accountId: JsonField, + private val authenticationType: JsonField, + private val companyId: JsonField, + private val products: JsonField>, + private val providerId: JsonField, + private val connectionId: JsonField, + private val additionalProperties: MutableMap, ) { - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + @JsonCreator + private constructor( + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("authentication_type") + @ExcludeMissing + authenticationType: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("products") + @ExcludeMissing + products: JsonField> = JsonMissing.of(), + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + ) : this( + accountId, + authenticationType, + companyId, + products, + providerId, + connectionId, + mutableMapOf(), + ) + + /** + * [DEPRECATED] Use `connection_id` to associate a connection with an access token + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun authenticationType(): AuthenticationType = authenticationType.getRequired("authentication_type") - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * [DEPRECATED] Use `connection_id` to associate a connection with an access token + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun products(): List = products.getRequired("products") - /** The ID of the provider associated with the `access_token` */ + /** + * The ID of the provider associated with the `access_token` + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun providerId(): String = providerId.getRequired("provider_id") - /** The ID of the new connection */ - fun connectionId(): Optional = - Optional.ofNullable(connectionId.getNullable("connection_id")) - - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * The ID of the new connection + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun connectionId(): Optional = connectionId.getOptional("connection_id") + + /** + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. + */ @Deprecated("deprecated") @JsonProperty("account_id") @ExcludeMissing fun _accountId(): JsonField = accountId + /** + * Returns the raw JSON value of [authenticationType]. + * + * Unlike [authenticationType], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("authentication_type") @ExcludeMissing fun _authenticationType(): JsonField = authenticationType - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. + */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("products") @ExcludeMissing fun _products(): JsonField> = products - /** The ID of the provider associated with the `access_token` */ + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("provider_id") @ExcludeMissing fun _providerId(): JsonField = providerId - /** The ID of the new connection */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AccountUpdateResponse = apply { - if (validated) { - return@apply - } - - accountId() - authenticationType() - companyId() - products() - providerId() - connectionId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [AccountUpdateResponse]. + * + * The following fields are required: + * ```java + * .accountId() + * .authenticationType() + * .companyId() + * .products() + * .providerId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -141,13 +210,26 @@ private constructor( @Deprecated("deprecated") fun accountId(accountId: String) = accountId(JsonField.of(accountId)) - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } fun authenticationType(authenticationType: AuthenticationType) = authenticationType(JsonField.of(authenticationType)) + /** + * Sets [Builder.authenticationType] to an arbitrary JSON value. + * + * You should usually call [Builder.authenticationType] with a well-typed + * [AuthenticationType] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun authenticationType(authenticationType: JsonField) = apply { this.authenticationType = authenticationType } @@ -156,39 +238,63 @@ private constructor( @Deprecated("deprecated") fun companyId(companyId: String) = companyId(JsonField.of(companyId)) - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } fun products(products: List) = products(JsonField.of(products)) + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun products(products: JsonField>) = apply { this.products = products.map { it.toMutableList() } } + /** + * Adds a single [String] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addProduct(product: String) = apply { products = - (products ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(product) + (products ?: JsonField.of(mutableListOf())).also { + checkKnown("products", it).add(product) } } /** The ID of the provider associated with the `access_token` */ fun providerId(providerId: String) = providerId(JsonField.of(providerId)) - /** The ID of the provider associated with the `access_token` */ + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun providerId(providerId: JsonField) = apply { this.providerId = providerId } /** The ID of the new connection */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** The ID of the new connection */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } @@ -212,6 +318,22 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [AccountUpdateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accountId() + * .authenticationType() + * .companyId() + * .products() + * .providerId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): AccountUpdateResponse = AccountUpdateResponse( checkRequired("accountId", accountId), @@ -220,10 +342,48 @@ private constructor( checkRequired("products", products).map { it.toImmutable() }, checkRequired("providerId", providerId), connectionId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): AccountUpdateResponse = apply { + if (validated) { + return@apply + } + + accountId() + authenticationType().validate() + companyId() + products() + providerId() + connectionId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountId.asKnown().isPresent) 1 else 0) + + (authenticationType.asKnown().getOrNull()?.validity() ?: 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (products.asKnown().getOrNull()?.size ?: 0) + + (if (providerId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + class AuthenticationType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -325,6 +485,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): AuthenticationType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AutomatedAsyncJob.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AutomatedAsyncJob.kt index 4a7fd197..d608907b 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AutomatedAsyncJob.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AutomatedAsyncJob.kt @@ -11,147 +11,233 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class AutomatedAsyncJob -@JsonCreator private constructor( - @JsonProperty("completed_at") - @ExcludeMissing - private val completedAt: JsonField = JsonMissing.of(), - @JsonProperty("created_at") - @ExcludeMissing - private val createdAt: JsonField = JsonMissing.of(), - @JsonProperty("job_id") @ExcludeMissing private val jobId: JsonField = JsonMissing.of(), - @JsonProperty("job_url") - @ExcludeMissing - private val jobUrl: JsonField = JsonMissing.of(), - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("scheduled_at") - @ExcludeMissing - private val scheduledAt: JsonField = JsonMissing.of(), - @JsonProperty("started_at") - @ExcludeMissing - private val startedAt: JsonField = JsonMissing.of(), - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val completedAt: JsonField, + private val createdAt: JsonField, + private val jobId: JsonField, + private val jobUrl: JsonField, + private val params: JsonField, + private val scheduledAt: JsonField, + private val startedAt: JsonField, + private val status: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The datetime the job completed. */ - fun completedAt(): Optional = - Optional.ofNullable(completedAt.getNullable("completed_at")) + @JsonCreator + private constructor( + @JsonProperty("completed_at") + @ExcludeMissing + completedAt: JsonField = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("job_id") @ExcludeMissing jobId: JsonField = JsonMissing.of(), + @JsonProperty("job_url") @ExcludeMissing jobUrl: JsonField = JsonMissing.of(), + @JsonProperty("params") @ExcludeMissing params: JsonField = JsonMissing.of(), + @JsonProperty("scheduled_at") + @ExcludeMissing + scheduledAt: JsonField = JsonMissing.of(), + @JsonProperty("started_at") + @ExcludeMissing + startedAt: JsonField = JsonMissing.of(), + @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this( + completedAt, + createdAt, + jobId, + jobUrl, + params, + scheduledAt, + startedAt, + status, + type, + mutableMapOf(), + ) + + /** + * The datetime the job completed. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun completedAt(): Optional = completedAt.getOptional("completed_at") /** * The datetime when the job was created. for scheduled jobs, this will be the initial * connection time. For ad-hoc jobs, this will be the time the creation request was received. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") - /** The id of the job that has been created. */ + /** + * The id of the job that has been created. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun jobId(): String = jobId.getRequired("job_id") - /** The url that can be used to retrieve the job status */ + /** + * The url that can be used to retrieve the job status + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun jobUrl(): String = jobUrl.getRequired("job_url") - /** The input parameters for the job. */ - fun params(): Optional = Optional.ofNullable(params.getNullable("params")) + /** + * The input parameters for the job. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun params(): Optional = params.getOptional("params") /** * The datetime a job is scheduled to be run. For scheduled jobs, this datetime can be in the * future if the job has not yet been enqueued. For ad-hoc jobs, this field will be null. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun scheduledAt(): Optional = - Optional.ofNullable(scheduledAt.getNullable("scheduled_at")) + fun scheduledAt(): Optional = scheduledAt.getOptional("scheduled_at") - /** The datetime a job entered into the job queue. */ - fun startedAt(): Optional = - Optional.ofNullable(startedAt.getNullable("started_at")) + /** + * The datetime a job entered into the job queue. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun startedAt(): Optional = startedAt.getOptional("started_at") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun status(): Status = status.getRequired("status") - /** The type of automated job */ + /** + * The type of automated job + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun type(): Type = type.getRequired("type") - /** The datetime the job completed. */ + /** + * Returns the raw JSON value of [completedAt]. + * + * Unlike [completedAt], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("completed_at") @ExcludeMissing fun _completedAt(): JsonField = completedAt /** - * The datetime when the job was created. for scheduled jobs, this will be the initial - * connection time. For ad-hoc jobs, this will be the time the creation request was received. + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("created_at") @ExcludeMissing fun _createdAt(): JsonField = createdAt - /** The id of the job that has been created. */ + /** + * Returns the raw JSON value of [jobId]. + * + * Unlike [jobId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("job_id") @ExcludeMissing fun _jobId(): JsonField = jobId - /** The url that can be used to retrieve the job status */ + /** + * Returns the raw JSON value of [jobUrl]. + * + * Unlike [jobUrl], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("job_url") @ExcludeMissing fun _jobUrl(): JsonField = jobUrl - /** The input parameters for the job. */ + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params /** - * The datetime a job is scheduled to be run. For scheduled jobs, this datetime can be in the - * future if the job has not yet been enqueued. For ad-hoc jobs, this field will be null. + * Returns the raw JSON value of [scheduledAt]. + * + * Unlike [scheduledAt], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("scheduled_at") @ExcludeMissing fun _scheduledAt(): JsonField = scheduledAt - /** The datetime a job entered into the job queue. */ + /** + * Returns the raw JSON value of [startedAt]. + * + * Unlike [startedAt], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("started_at") @ExcludeMissing fun _startedAt(): JsonField = startedAt + /** + * Returns the raw JSON value of [status]. + * + * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status - /** The type of automated job */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AutomatedAsyncJob = apply { - if (validated) { - return@apply - } - - completedAt() - createdAt() - jobId() - jobUrl() - params().ifPresent { it.validate() } - scheduledAt() - startedAt() - status() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [AutomatedAsyncJob]. + * + * The following fields are required: + * ```java + * .completedAt() + * .createdAt() + * .jobId() + * .jobUrl() + * .params() + * .scheduledAt() + * .startedAt() + * .status() + * .type() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -187,11 +273,17 @@ private constructor( fun completedAt(completedAt: OffsetDateTime?) = completedAt(JsonField.ofNullable(completedAt)) - /** The datetime the job completed. */ + /** Alias for calling [Builder.completedAt] with `completedAt.orElse(null)`. */ fun completedAt(completedAt: Optional) = - completedAt(completedAt.orElse(null)) + completedAt(completedAt.getOrNull()) - /** The datetime the job completed. */ + /** + * Sets [Builder.completedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.completedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun completedAt(completedAt: JsonField) = apply { this.completedAt = completedAt } @@ -204,31 +296,48 @@ private constructor( fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) /** - * The datetime when the job was created. for scheduled jobs, this will be the initial - * connection time. For ad-hoc jobs, this will be the time the creation request was - * received. + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } /** The id of the job that has been created. */ fun jobId(jobId: String) = jobId(JsonField.of(jobId)) - /** The id of the job that has been created. */ + /** + * Sets [Builder.jobId] to an arbitrary JSON value. + * + * You should usually call [Builder.jobId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun jobId(jobId: JsonField) = apply { this.jobId = jobId } /** The url that can be used to retrieve the job status */ fun jobUrl(jobUrl: String) = jobUrl(JsonField.of(jobUrl)) - /** The url that can be used to retrieve the job status */ + /** + * Sets [Builder.jobUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.jobUrl] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun jobUrl(jobUrl: JsonField) = apply { this.jobUrl = jobUrl } /** The input parameters for the job. */ fun params(params: Params?) = params(JsonField.ofNullable(params)) - /** The input parameters for the job. */ - fun params(params: Optional) = params(params.orElse(null)) + /** Alias for calling [Builder.params] with `params.orElse(null)`. */ + fun params(params: Optional) = params(params.getOrNull()) - /** The input parameters for the job. */ + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun params(params: JsonField) = apply { this.params = params } /** @@ -239,18 +348,16 @@ private constructor( fun scheduledAt(scheduledAt: OffsetDateTime?) = scheduledAt(JsonField.ofNullable(scheduledAt)) - /** - * The datetime a job is scheduled to be run. For scheduled jobs, this datetime can be in - * the future if the job has not yet been enqueued. For ad-hoc jobs, this field will - * be null. - */ + /** Alias for calling [Builder.scheduledAt] with `scheduledAt.orElse(null)`. */ fun scheduledAt(scheduledAt: Optional) = - scheduledAt(scheduledAt.orElse(null)) + scheduledAt(scheduledAt.getOrNull()) /** - * The datetime a job is scheduled to be run. For scheduled jobs, this datetime can be in - * the future if the job has not yet been enqueued. For ad-hoc jobs, this field will - * be null. + * Sets [Builder.scheduledAt] to an arbitrary JSON value. + * + * You should usually call [Builder.scheduledAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun scheduledAt(scheduledAt: JsonField) = apply { this.scheduledAt = scheduledAt @@ -259,20 +366,37 @@ private constructor( /** The datetime a job entered into the job queue. */ fun startedAt(startedAt: OffsetDateTime?) = startedAt(JsonField.ofNullable(startedAt)) - /** The datetime a job entered into the job queue. */ - fun startedAt(startedAt: Optional) = startedAt(startedAt.orElse(null)) + /** Alias for calling [Builder.startedAt] with `startedAt.orElse(null)`. */ + fun startedAt(startedAt: Optional) = startedAt(startedAt.getOrNull()) - /** The datetime a job entered into the job queue. */ + /** + * Sets [Builder.startedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.startedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun startedAt(startedAt: JsonField) = apply { this.startedAt = startedAt } fun status(status: Status) = status(JsonField.of(status)) + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [Status] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun status(status: JsonField) = apply { this.status = status } /** The type of automated job */ fun type(type: Type) = type(JsonField.of(type)) - /** The type of automated job */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -294,6 +418,26 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [AutomatedAsyncJob]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .completedAt() + * .createdAt() + * .jobId() + * .jobUrl() + * .params() + * .scheduledAt() + * .startedAt() + * .status() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): AutomatedAsyncJob = AutomatedAsyncJob( checkRequired("completedAt", completedAt), @@ -305,50 +449,101 @@ private constructor( checkRequired("startedAt", startedAt), checkRequired("status", status), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): AutomatedAsyncJob = apply { + if (validated) { + return@apply + } + + completedAt() + createdAt() + jobId() + jobUrl() + params().ifPresent { it.validate() } + scheduledAt() + startedAt() + status().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (completedAt.asKnown().isPresent) 1 else 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (jobId.asKnown().isPresent) 1 else 0) + + (if (jobUrl.asKnown().isPresent) 1 else 0) + + (params.asKnown().getOrNull()?.validity() ?: 0) + + (if (scheduledAt.asKnown().isPresent) 1 else 0) + + (if (startedAt.asKnown().isPresent) 1 else 0) + + (status.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + /** The input parameters for the job. */ - @NoAutoDetect class Params - @JsonCreator private constructor( - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val individualId: JsonField, + private val additionalProperties: MutableMap, ) { - /** The ID of the individual that the job was completed for. */ - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) + @JsonCreator + private constructor( + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of() + ) : this(individualId, mutableMapOf()) - /** The ID of the individual that the job was completed for. */ + /** + * The ID of the individual that the job was completed for. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") + + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - individualId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Params]. */ @JvmStatic fun builder() = Builder() } @@ -367,7 +562,13 @@ private constructor( /** The ID of the individual that the job was completed for. */ fun individualId(individualId: String) = individualId(JsonField.of(individualId)) - /** The ID of the individual that the job was completed for. */ + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -391,9 +592,42 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Params = Params(individualId, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Params = Params(individualId, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + individualId() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (individualId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -520,6 +754,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Status = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -618,6 +879,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AutomatedCreateResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AutomatedCreateResponse.kt index ea36d6ea..35b96448 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AutomatedCreateResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AutomatedCreateResponse.kt @@ -10,79 +10,123 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects -@NoAutoDetect class AutomatedCreateResponse -@JsonCreator private constructor( - @JsonProperty("allowed_refreshes") - @ExcludeMissing - private val allowedRefreshes: JsonField = JsonMissing.of(), - @JsonProperty("job_id") @ExcludeMissing private val jobId: JsonField = JsonMissing.of(), - @JsonProperty("job_url") - @ExcludeMissing - private val jobUrl: JsonField = JsonMissing.of(), - @JsonProperty("remaining_refreshes") - @ExcludeMissing - private val remainingRefreshes: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val allowedRefreshes: JsonField, + private val jobId: JsonField, + private val jobUrl: JsonField, + private val remainingRefreshes: JsonField, + private val additionalProperties: MutableMap, ) { - /** The number of allowed refreshes per hour (per hour, fixed window) */ + @JsonCreator + private constructor( + @JsonProperty("allowed_refreshes") + @ExcludeMissing + allowedRefreshes: JsonField = JsonMissing.of(), + @JsonProperty("job_id") @ExcludeMissing jobId: JsonField = JsonMissing.of(), + @JsonProperty("job_url") @ExcludeMissing jobUrl: JsonField = JsonMissing.of(), + @JsonProperty("remaining_refreshes") + @ExcludeMissing + remainingRefreshes: JsonField = JsonMissing.of(), + ) : this(allowedRefreshes, jobId, jobUrl, remainingRefreshes, mutableMapOf()) + + /** + * The number of allowed refreshes per hour (per hour, fixed window) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun allowedRefreshes(): Long = allowedRefreshes.getRequired("allowed_refreshes") - /** The id of the job that has been created. */ + /** + * The id of the job that has been created. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun jobId(): String = jobId.getRequired("job_id") - /** The url that can be used to retrieve the job status */ + /** + * The url that can be used to retrieve the job status + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun jobUrl(): String = jobUrl.getRequired("job_url") - /** The number of remaining refreshes available (per hour, fixed window) */ + /** + * The number of remaining refreshes available (per hour, fixed window) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun remainingRefreshes(): Long = remainingRefreshes.getRequired("remaining_refreshes") - /** The number of allowed refreshes per hour (per hour, fixed window) */ + /** + * Returns the raw JSON value of [allowedRefreshes]. + * + * Unlike [allowedRefreshes], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("allowed_refreshes") @ExcludeMissing fun _allowedRefreshes(): JsonField = allowedRefreshes - /** The id of the job that has been created. */ + /** + * Returns the raw JSON value of [jobId]. + * + * Unlike [jobId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("job_id") @ExcludeMissing fun _jobId(): JsonField = jobId - /** The url that can be used to retrieve the job status */ + /** + * Returns the raw JSON value of [jobUrl]. + * + * Unlike [jobUrl], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("job_url") @ExcludeMissing fun _jobUrl(): JsonField = jobUrl - /** The number of remaining refreshes available (per hour, fixed window) */ + /** + * Returns the raw JSON value of [remainingRefreshes]. + * + * Unlike [remainingRefreshes], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("remaining_refreshes") @ExcludeMissing fun _remainingRefreshes(): JsonField = remainingRefreshes + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AutomatedCreateResponse = apply { - if (validated) { - return@apply - } - - allowedRefreshes() - jobId() - jobUrl() - remainingRefreshes() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [AutomatedCreateResponse]. + * + * The following fields are required: + * ```java + * .allowedRefreshes() + * .jobId() + * .jobUrl() + * .remainingRefreshes() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -108,7 +152,13 @@ private constructor( fun allowedRefreshes(allowedRefreshes: Long) = allowedRefreshes(JsonField.of(allowedRefreshes)) - /** The number of allowed refreshes per hour (per hour, fixed window) */ + /** + * Sets [Builder.allowedRefreshes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedRefreshes] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun allowedRefreshes(allowedRefreshes: JsonField) = apply { this.allowedRefreshes = allowedRefreshes } @@ -116,20 +166,36 @@ private constructor( /** The id of the job that has been created. */ fun jobId(jobId: String) = jobId(JsonField.of(jobId)) - /** The id of the job that has been created. */ + /** + * Sets [Builder.jobId] to an arbitrary JSON value. + * + * You should usually call [Builder.jobId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun jobId(jobId: JsonField) = apply { this.jobId = jobId } /** The url that can be used to retrieve the job status */ fun jobUrl(jobUrl: String) = jobUrl(JsonField.of(jobUrl)) - /** The url that can be used to retrieve the job status */ + /** + * Sets [Builder.jobUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.jobUrl] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun jobUrl(jobUrl: JsonField) = apply { this.jobUrl = jobUrl } /** The number of remaining refreshes available (per hour, fixed window) */ fun remainingRefreshes(remainingRefreshes: Long) = remainingRefreshes(JsonField.of(remainingRefreshes)) - /** The number of remaining refreshes available (per hour, fixed window) */ + /** + * Sets [Builder.remainingRefreshes] to an arbitrary JSON value. + * + * You should usually call [Builder.remainingRefreshes] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun remainingRefreshes(remainingRefreshes: JsonField) = apply { this.remainingRefreshes = remainingRefreshes } @@ -153,16 +219,65 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [AutomatedCreateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .allowedRefreshes() + * .jobId() + * .jobUrl() + * .remainingRefreshes() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): AutomatedCreateResponse = AutomatedCreateResponse( checkRequired("allowedRefreshes", allowedRefreshes), checkRequired("jobId", jobId), checkRequired("jobUrl", jobUrl), checkRequired("remainingRefreshes", remainingRefreshes), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): AutomatedCreateResponse = apply { + if (validated) { + return@apply + } + + allowedRefreshes() + jobId() + jobUrl() + remainingRefreshes() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (allowedRefreshes.asKnown().isPresent) 1 else 0) + + (if (jobId.asKnown().isPresent) 1 else 0) + + (if (jobUrl.asKnown().isPresent) 1 else 0) + + (if (remainingRefreshes.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AutomatedListResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AutomatedListResponse.kt new file mode 100644 index 00000000..d93686fc --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/AutomatedListResponse.kt @@ -0,0 +1,717 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.tryfinch.api.core.ExcludeMissing +import com.tryfinch.api.core.JsonField +import com.tryfinch.api.core.JsonMissing +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.checkKnown +import com.tryfinch.api.core.checkRequired +import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class AutomatedListResponse +private constructor( + private val data: JsonField>, + private val meta: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("data") + @ExcludeMissing + data: JsonField> = JsonMissing.of(), + @JsonProperty("meta") @ExcludeMissing meta: JsonField = JsonMissing.of(), + ) : this(data, meta, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun data(): List = data.getRequired("data") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ + fun meta(): Meta = meta.getRequired("meta") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField> = data + + /** + * Returns the raw JSON value of [meta]. + * + * Unlike [meta], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("meta") @ExcludeMissing fun _meta(): JsonField = meta + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AutomatedListResponse]. + * + * The following fields are required: + * ```java + * .data() + * .meta() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AutomatedListResponse]. */ + class Builder internal constructor() { + + private var data: JsonField>? = null + private var meta: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(automatedListResponse: AutomatedListResponse) = apply { + data = automatedListResponse.data.map { it.toMutableList() } + meta = automatedListResponse.meta + additionalProperties = automatedListResponse.additionalProperties.toMutableMap() + } + + fun data(data: List) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun data(data: JsonField>) = apply { + this.data = data.map { it.toMutableList() } + } + + /** + * Adds a single [AutomatedAsyncJob] to [Builder.data]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addData(data: AutomatedAsyncJob) = apply { + this.data = + (this.data ?: JsonField.of(mutableListOf())).also { + checkKnown("data", it).add(data) + } + } + + fun meta(meta: Meta) = meta(JsonField.of(meta)) + + /** + * Sets [Builder.meta] to an arbitrary JSON value. + * + * You should usually call [Builder.meta] with a well-typed [Meta] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun meta(meta: JsonField) = apply { this.meta = meta } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AutomatedListResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .data() + * .meta() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AutomatedListResponse = + AutomatedListResponse( + checkRequired("data", data).map { it.toImmutable() }, + checkRequired("meta", meta), + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): AutomatedListResponse = apply { + if (validated) { + return@apply + } + + data().forEach { it.validate() } + meta().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (data.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (meta.asKnown().getOrNull()?.validity() ?: 0) + + class Meta + private constructor( + private val quotas: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("quotas") @ExcludeMissing quotas: JsonField = JsonMissing.of() + ) : this(quotas, mutableMapOf()) + + /** + * Information about remaining quotas for this connection. Only applicable for customers + * opted in to use Finch's Data Sync Refresh endpoint (`POST /jobs/automated`). Please + * contact a Finch representative for more details. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun quotas(): Optional = quotas.getOptional("quotas") + + /** + * Returns the raw JSON value of [quotas]. + * + * Unlike [quotas], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("quotas") @ExcludeMissing fun _quotas(): JsonField = quotas + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Meta]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Meta]. */ + class Builder internal constructor() { + + private var quotas: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(meta: Meta) = apply { + quotas = meta.quotas + additionalProperties = meta.additionalProperties.toMutableMap() + } + + /** + * Information about remaining quotas for this connection. Only applicable for customers + * opted in to use Finch's Data Sync Refresh endpoint (`POST /jobs/automated`). Please + * contact a Finch representative for more details. + */ + fun quotas(quotas: Quotas) = quotas(JsonField.of(quotas)) + + /** + * Sets [Builder.quotas] to an arbitrary JSON value. + * + * You should usually call [Builder.quotas] with a well-typed [Quotas] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun quotas(quotas: JsonField) = apply { this.quotas = quotas } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Meta]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Meta = Meta(quotas, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Meta = apply { + if (validated) { + return@apply + } + + quotas().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (quotas.asKnown().getOrNull()?.validity() ?: 0) + + /** + * Information about remaining quotas for this connection. Only applicable for customers + * opted in to use Finch's Data Sync Refresh endpoint (`POST /jobs/automated`). Please + * contact a Finch representative for more details. + */ + class Quotas + private constructor( + private val dataSyncAll: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("data_sync_all") + @ExcludeMissing + dataSyncAll: JsonField = JsonMissing.of() + ) : this(dataSyncAll, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun dataSyncAll(): Optional = dataSyncAll.getOptional("data_sync_all") + + /** + * Returns the raw JSON value of [dataSyncAll]. + * + * Unlike [dataSyncAll], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("data_sync_all") + @ExcludeMissing + fun _dataSyncAll(): JsonField = dataSyncAll + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Quotas]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Quotas]. */ + class Builder internal constructor() { + + private var dataSyncAll: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(quotas: Quotas) = apply { + dataSyncAll = quotas.dataSyncAll + additionalProperties = quotas.additionalProperties.toMutableMap() + } + + fun dataSyncAll(dataSyncAll: DataSyncAll) = dataSyncAll(JsonField.of(dataSyncAll)) + + /** + * Sets [Builder.dataSyncAll] to an arbitrary JSON value. + * + * You should usually call [Builder.dataSyncAll] with a well-typed [DataSyncAll] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun dataSyncAll(dataSyncAll: JsonField) = apply { + this.dataSyncAll = dataSyncAll + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Quotas]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Quotas = Quotas(dataSyncAll, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Quotas = apply { + if (validated) { + return@apply + } + + dataSyncAll().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (dataSyncAll.asKnown().getOrNull()?.validity() ?: 0) + + class DataSyncAll + private constructor( + private val allowedRefreshes: JsonField, + private val remainingRefreshes: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("allowed_refreshes") + @ExcludeMissing + allowedRefreshes: JsonField = JsonMissing.of(), + @JsonProperty("remaining_refreshes") + @ExcludeMissing + remainingRefreshes: JsonField = JsonMissing.of(), + ) : this(allowedRefreshes, remainingRefreshes, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun allowedRefreshes(): Optional = + allowedRefreshes.getOptional("allowed_refreshes") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun remainingRefreshes(): Optional = + remainingRefreshes.getOptional("remaining_refreshes") + + /** + * Returns the raw JSON value of [allowedRefreshes]. + * + * Unlike [allowedRefreshes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("allowed_refreshes") + @ExcludeMissing + fun _allowedRefreshes(): JsonField = allowedRefreshes + + /** + * Returns the raw JSON value of [remainingRefreshes]. + * + * Unlike [remainingRefreshes], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("remaining_refreshes") + @ExcludeMissing + fun _remainingRefreshes(): JsonField = remainingRefreshes + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [DataSyncAll]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [DataSyncAll]. */ + class Builder internal constructor() { + + private var allowedRefreshes: JsonField = JsonMissing.of() + private var remainingRefreshes: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(dataSyncAll: DataSyncAll) = apply { + allowedRefreshes = dataSyncAll.allowedRefreshes + remainingRefreshes = dataSyncAll.remainingRefreshes + additionalProperties = dataSyncAll.additionalProperties.toMutableMap() + } + + fun allowedRefreshes(allowedRefreshes: Long) = + allowedRefreshes(JsonField.of(allowedRefreshes)) + + /** + * Sets [Builder.allowedRefreshes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedRefreshes] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun allowedRefreshes(allowedRefreshes: JsonField) = apply { + this.allowedRefreshes = allowedRefreshes + } + + fun remainingRefreshes(remainingRefreshes: Long) = + remainingRefreshes(JsonField.of(remainingRefreshes)) + + /** + * Sets [Builder.remainingRefreshes] to an arbitrary JSON value. + * + * You should usually call [Builder.remainingRefreshes] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun remainingRefreshes(remainingRefreshes: JsonField) = apply { + this.remainingRefreshes = remainingRefreshes + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [DataSyncAll]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): DataSyncAll = + DataSyncAll( + allowedRefreshes, + remainingRefreshes, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): DataSyncAll = apply { + if (validated) { + return@apply + } + + allowedRefreshes() + remainingRefreshes() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (allowedRefreshes.asKnown().isPresent) 1 else 0) + + (if (remainingRefreshes.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is DataSyncAll && allowedRefreshes == other.allowedRefreshes && remainingRefreshes == other.remainingRefreshes && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(allowedRefreshes, remainingRefreshes, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "DataSyncAll{allowedRefreshes=$allowedRefreshes, remainingRefreshes=$remainingRefreshes, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Quotas && dataSyncAll == other.dataSyncAll && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(dataSyncAll, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Quotas{dataSyncAll=$dataSyncAll, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Meta && quotas == other.quotas && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(quotas, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = "Meta{quotas=$quotas, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is AutomatedListResponse && data == other.data && meta == other.meta && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(data, meta, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AutomatedListResponse{data=$data, meta=$meta, additionalProperties=$additionalProperties}" +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BaseWebhookEvent.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BaseWebhookEvent.kt index 51555300..509f3391 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BaseWebhookEvent.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BaseWebhookEvent.kt @@ -10,48 +10,59 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional -@NoAutoDetect class BaseWebhookEvent -@JsonCreator private constructor( - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accountId: JsonField, + private val companyId: JsonField, + private val connectionId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + ) : this(accountId, companyId, connectionId, mutableMapOf()) + /** * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") /** * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") - /** Unique Finch ID of the connection associated with the webhook event. */ - fun connectionId(): Optional = - Optional.ofNullable(connectionId.getNullable("connection_id")) + /** + * Unique Finch ID of the connection associated with the webhook event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun connectionId(): Optional = connectionId.getOptional("connection_id") /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("account_id") @@ -59,40 +70,47 @@ private constructor( fun _accountId(): JsonField = accountId /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): BaseWebhookEvent = apply { - if (validated) { - return@apply - } - - accountId() - companyId() - connectionId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [BaseWebhookEvent]. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -120,8 +138,11 @@ private constructor( fun accountId(accountId: String) = accountId(JsonField.of(accountId)) /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } @@ -134,8 +155,11 @@ private constructor( fun companyId(companyId: String) = companyId(JsonField.of(companyId)) /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } @@ -143,7 +167,13 @@ private constructor( /** Unique Finch ID of the connection associated with the webhook event. */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } @@ -167,15 +197,60 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [BaseWebhookEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): BaseWebhookEvent = BaseWebhookEvent( checkRequired("accountId", accountId), checkRequired("companyId", companyId), connectionId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): BaseWebhookEvent = apply { + if (validated) { + return@apply + } + + accountId() + companyId() + connectionId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountId.asKnown().isPresent) 1 else 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitContribution.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitContribution.kt index bfef1c4b..7c842ee6 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitContribution.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitContribution.kt @@ -11,54 +11,70 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class BenefitContribution -@JsonCreator private constructor( - @JsonProperty("amount") @ExcludeMissing private val amount: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val amount: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** Contribution amount in cents (if `fixed`) or basis points (if `percent`). */ - fun amount(): Optional = Optional.ofNullable(amount.getNullable("amount")) - - /** Contribution type. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** Contribution amount in cents (if `fixed`) or basis points (if `percent`). */ + @JsonCreator + private constructor( + @JsonProperty("amount") @ExcludeMissing amount: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(amount, type, mutableMapOf()) + + /** + * Contribution amount in cents (if `fixed`) or basis points (if `percent`). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") + + /** + * Contribution type. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount - /** Contribution type. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): BenefitContribution = apply { - if (validated) { - return@apply - } - - amount() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [BenefitContribution]. */ @JvmStatic fun builder() = Builder() } @@ -79,23 +95,36 @@ private constructor( /** Contribution amount in cents (if `fixed`) or basis points (if `percent`). */ fun amount(amount: Long?) = amount(JsonField.ofNullable(amount)) - /** Contribution amount in cents (if `fixed`) or basis points (if `percent`). */ + /** + * Alias for [Builder.amount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun amount(amount: Long) = amount(amount as Long?) - /** Contribution amount in cents (if `fixed`) or basis points (if `percent`). */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun amount(amount: Optional) = amount(amount.orElse(null) as Long?) + /** Alias for calling [Builder.amount] with `amount.orElse(null)`. */ + fun amount(amount: Optional) = amount(amount.getOrNull()) - /** Contribution amount in cents (if `fixed`) or basis points (if `percent`). */ + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } /** Contribution type. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** Contribution type. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** Contribution type. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -117,10 +146,44 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [BenefitContribution]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): BenefitContribution = - BenefitContribution(amount, type, additionalProperties.toImmutable()) + BenefitContribution(amount, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): BenefitContribution = apply { + if (validated) { + return@apply + } + + amount() + type().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + (type.asKnown().getOrNull()?.validity() ?: 0) + /** Contribution type. */ class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -206,6 +269,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitFeaturesAndOperations.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitFeaturesAndOperations.kt index e59b1426..2d9f9c47 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitFeaturesAndOperations.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitFeaturesAndOperations.kt @@ -11,60 +11,82 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class BenefitFeaturesAndOperations -@JsonCreator private constructor( - @JsonProperty("supported_features") - @ExcludeMissing - private val supportedFeatures: JsonField = JsonMissing.of(), - @JsonProperty("supported_operations") - @ExcludeMissing - private val supportedOperations: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val supportedFeatures: JsonField, + private val supportedOperations: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("supported_features") + @ExcludeMissing + supportedFeatures: JsonField = JsonMissing.of(), + @JsonProperty("supported_operations") + @ExcludeMissing + supportedOperations: JsonField = JsonMissing.of(), + ) : this(supportedFeatures, supportedOperations, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun supportedFeatures(): Optional = - Optional.ofNullable(supportedFeatures.getNullable("supported_features")) + supportedFeatures.getOptional("supported_features") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun supportedOperations(): Optional = - Optional.ofNullable(supportedOperations.getNullable("supported_operations")) - + supportedOperations.getOptional("supported_operations") + + /** + * Returns the raw JSON value of [supportedFeatures]. + * + * Unlike [supportedFeatures], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("supported_features") @ExcludeMissing fun _supportedFeatures(): JsonField = supportedFeatures + /** + * Returns the raw JSON value of [supportedOperations]. + * + * Unlike [supportedOperations], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("supported_operations") @ExcludeMissing fun _supportedOperations(): JsonField = supportedOperations + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): BenefitFeaturesAndOperations = apply { - if (validated) { - return@apply - } - - supportedFeatures().ifPresent { it.validate() } - supportedOperations().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [BenefitFeaturesAndOperations]. + */ @JvmStatic fun builder() = Builder() } @@ -85,6 +107,13 @@ private constructor( fun supportedFeatures(supportedFeatures: BenefitFeature) = supportedFeatures(JsonField.of(supportedFeatures)) + /** + * Sets [Builder.supportedFeatures] to an arbitrary JSON value. + * + * You should usually call [Builder.supportedFeatures] with a well-typed [BenefitFeature] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun supportedFeatures(supportedFeatures: JsonField) = apply { this.supportedFeatures = supportedFeatures } @@ -92,6 +121,13 @@ private constructor( fun supportedOperations(supportedOperations: SupportPerBenefitType) = supportedOperations(JsonField.of(supportedOperations)) + /** + * Sets [Builder.supportedOperations] to an arbitrary JSON value. + * + * You should usually call [Builder.supportedOperations] with a well-typed + * [SupportPerBenefitType] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ fun supportedOperations(supportedOperations: JsonField) = apply { this.supportedOperations = supportedOperations } @@ -115,142 +151,235 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [BenefitFeaturesAndOperations]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): BenefitFeaturesAndOperations = BenefitFeaturesAndOperations( supportedFeatures, supportedOperations, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): BenefitFeaturesAndOperations = apply { + if (validated) { + return@apply + } + + supportedFeatures().ifPresent { it.validate() } + supportedOperations().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (supportedFeatures.asKnown().getOrNull()?.validity() ?: 0) + + (supportedOperations.asKnown().getOrNull()?.validity() ?: 0) + class BenefitFeature - @JsonCreator private constructor( - @JsonProperty("annual_maximum") - @ExcludeMissing - private val annualMaximum: JsonField = JsonMissing.of(), - @JsonProperty("catch_up") - @ExcludeMissing - private val catchUp: JsonField = JsonMissing.of(), - @JsonProperty("company_contribution") - @ExcludeMissing - private val companyContribution: JsonField> = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("employee_deduction") - @ExcludeMissing - private val employeeDeduction: JsonField> = JsonMissing.of(), - @JsonProperty("frequencies") - @ExcludeMissing - private val frequencies: JsonField> = JsonMissing.of(), - @JsonProperty("hsa_contribution_limit") - @ExcludeMissing - private val hsaContributionLimit: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val annualMaximum: JsonField, + private val catchUp: JsonField, + private val companyContribution: JsonField>, + private val description: JsonField, + private val employeeDeduction: JsonField>, + private val frequencies: JsonField>, + private val hsaContributionLimit: JsonField>, + private val additionalProperties: MutableMap, ) { - /** Whether the provider supports an annual maximum for this benefit. */ - fun annualMaximum(): Optional = - Optional.ofNullable(annualMaximum.getNullable("annual_maximum")) + @JsonCreator + private constructor( + @JsonProperty("annual_maximum") + @ExcludeMissing + annualMaximum: JsonField = JsonMissing.of(), + @JsonProperty("catch_up") + @ExcludeMissing + catchUp: JsonField = JsonMissing.of(), + @JsonProperty("company_contribution") + @ExcludeMissing + companyContribution: JsonField> = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("employee_deduction") + @ExcludeMissing + employeeDeduction: JsonField> = JsonMissing.of(), + @JsonProperty("frequencies") + @ExcludeMissing + frequencies: JsonField> = JsonMissing.of(), + @JsonProperty("hsa_contribution_limit") + @ExcludeMissing + hsaContributionLimit: JsonField> = JsonMissing.of(), + ) : this( + annualMaximum, + catchUp, + companyContribution, + description, + employeeDeduction, + frequencies, + hsaContributionLimit, + mutableMapOf(), + ) + + /** + * Whether the provider supports an annual maximum for this benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun annualMaximum(): Optional = annualMaximum.getOptional("annual_maximum") /** * Whether the provider supports catch up for this benefit. This field will only be true for * retirement benefits. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun catchUp(): Optional = Optional.ofNullable(catchUp.getNullable("catch_up")) + fun catchUp(): Optional = catchUp.getOptional("catch_up") /** * Supported contribution types. An empty array indicates contributions are not supported. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ fun companyContribution(): Optional> = - Optional.ofNullable(companyContribution.getNullable("company_contribution")) + companyContribution.getOptional("company_contribution") - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") - /** Supported deduction types. An empty array indicates deductions are not supported. */ + /** + * Supported deduction types. An empty array indicates deductions are not supported. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun employeeDeduction(): Optional> = - Optional.ofNullable(employeeDeduction.getNullable("employee_deduction")) + employeeDeduction.getOptional("employee_deduction") - /** The list of frequencies supported by the provider for this benefit */ + /** + * The list of frequencies supported by the provider for this benefit + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun frequencies(): Optional> = - Optional.ofNullable(frequencies.getNullable("frequencies")) + frequencies.getOptional("frequencies") /** * Whether the provider supports HSA contribution limits. Empty if this feature is not * supported for the benefit. This array only has values for HSA benefits. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ fun hsaContributionLimit(): Optional> = - Optional.ofNullable(hsaContributionLimit.getNullable("hsa_contribution_limit")) + hsaContributionLimit.getOptional("hsa_contribution_limit") - /** Whether the provider supports an annual maximum for this benefit. */ + /** + * Returns the raw JSON value of [annualMaximum]. + * + * Unlike [annualMaximum], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("annual_maximum") @ExcludeMissing fun _annualMaximum(): JsonField = annualMaximum /** - * Whether the provider supports catch up for this benefit. This field will only be true for - * retirement benefits. + * Returns the raw JSON value of [catchUp]. + * + * Unlike [catchUp], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("catch_up") @ExcludeMissing fun _catchUp(): JsonField = catchUp /** - * Supported contribution types. An empty array indicates contributions are not supported. + * Returns the raw JSON value of [companyContribution]. + * + * Unlike [companyContribution], this method doesn't throw if the JSON field has an + * unexpected type. */ @JsonProperty("company_contribution") @ExcludeMissing fun _companyContribution(): JsonField> = companyContribution + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description - /** Supported deduction types. An empty array indicates deductions are not supported. */ + /** + * Returns the raw JSON value of [employeeDeduction]. + * + * Unlike [employeeDeduction], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("employee_deduction") @ExcludeMissing fun _employeeDeduction(): JsonField> = employeeDeduction - /** The list of frequencies supported by the provider for this benefit */ + /** + * Returns the raw JSON value of [frequencies]. + * + * Unlike [frequencies], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("frequencies") @ExcludeMissing fun _frequencies(): JsonField> = frequencies /** - * Whether the provider supports HSA contribution limits. Empty if this feature is not - * supported for the benefit. This array only has values for HSA benefits. + * Returns the raw JSON value of [hsaContributionLimit]. + * + * Unlike [hsaContributionLimit], this method doesn't throw if the JSON field has an + * unexpected type. */ @JsonProperty("hsa_contribution_limit") @ExcludeMissing fun _hsaContributionLimit(): JsonField> = hsaContributionLimit + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): BenefitFeature = apply { - if (validated) { - return@apply - } - - annualMaximum() - catchUp() - companyContribution() - description() - employeeDeduction() - frequencies() - hsaContributionLimit() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [BenefitFeature]. */ @JvmStatic fun builder() = Builder() } @@ -283,15 +412,24 @@ private constructor( fun annualMaximum(annualMaximum: Boolean?) = annualMaximum(JsonField.ofNullable(annualMaximum)) - /** Whether the provider supports an annual maximum for this benefit. */ + /** + * Alias for [Builder.annualMaximum]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun annualMaximum(annualMaximum: Boolean) = annualMaximum(annualMaximum as Boolean?) - /** Whether the provider supports an annual maximum for this benefit. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 + /** Alias for calling [Builder.annualMaximum] with `annualMaximum.orElse(null)`. */ fun annualMaximum(annualMaximum: Optional) = - annualMaximum(annualMaximum.orElse(null) as Boolean?) + annualMaximum(annualMaximum.getOrNull()) - /** Whether the provider supports an annual maximum for this benefit. */ + /** + * Sets [Builder.annualMaximum] to an arbitrary JSON value. + * + * You should usually call [Builder.annualMaximum] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun annualMaximum(annualMaximum: JsonField) = apply { this.annualMaximum = annualMaximum } @@ -303,21 +441,21 @@ private constructor( fun catchUp(catchUp: Boolean?) = catchUp(JsonField.ofNullable(catchUp)) /** - * Whether the provider supports catch up for this benefit. This field will only be true - * for retirement benefits. + * Alias for [Builder.catchUp]. + * + * This unboxed primitive overload exists for backwards compatibility. */ fun catchUp(catchUp: Boolean) = catchUp(catchUp as Boolean?) - /** - * Whether the provider supports catch up for this benefit. This field will only be true - * for retirement benefits. - */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun catchUp(catchUp: Optional) = catchUp(catchUp.orElse(null) as Boolean?) + /** Alias for calling [Builder.catchUp] with `catchUp.orElse(null)`. */ + fun catchUp(catchUp: Optional) = catchUp(catchUp.getOrNull()) /** - * Whether the provider supports catch up for this benefit. This field will only be true - * for retirement benefits. + * Sets [Builder.catchUp] to an arbitrary JSON value. + * + * You should usually call [Builder.catchUp] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun catchUp(catchUp: JsonField) = apply { this.catchUp = catchUp } @@ -329,15 +467,18 @@ private constructor( companyContribution(JsonField.ofNullable(companyContribution)) /** - * Supported contribution types. An empty array indicates contributions are not - * supported. + * Alias for calling [Builder.companyContribution] with + * `companyContribution.orElse(null)`. */ fun companyContribution(companyContribution: Optional>) = - companyContribution(companyContribution.orElse(null)) + companyContribution(companyContribution.getOrNull()) /** - * Supported contribution types. An empty array indicates contributions are not - * supported. + * Sets [Builder.companyContribution] to an arbitrary JSON value. + * + * You should usually call [Builder.companyContribution] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. */ fun companyContribution(companyContribution: JsonField>) = apply { @@ -345,26 +486,29 @@ private constructor( } /** - * Supported contribution types. An empty array indicates contributions are not - * supported. + * Adds a single [CompanyContribution] to [Builder.companyContribution]. + * + * @throws IllegalStateException if the field was previously set to a non-list. */ fun addCompanyContribution(companyContribution: CompanyContribution) = apply { this.companyContribution = - (this.companyContribution ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(companyContribution) + (this.companyContribution ?: JsonField.of(mutableListOf())).also { + checkKnown("companyContribution", it).add(companyContribution) } } fun description(description: String?) = description(JsonField.ofNullable(description)) - fun description(description: Optional) = description(description.orElse(null)) + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun description(description: JsonField) = apply { this.description = description } @@ -373,26 +517,32 @@ private constructor( fun employeeDeduction(employeeDeduction: List?) = employeeDeduction(JsonField.ofNullable(employeeDeduction)) - /** Supported deduction types. An empty array indicates deductions are not supported. */ + /** + * Alias for calling [Builder.employeeDeduction] with `employeeDeduction.orElse(null)`. + */ fun employeeDeduction(employeeDeduction: Optional>) = - employeeDeduction(employeeDeduction.orElse(null)) + employeeDeduction(employeeDeduction.getOrNull()) - /** Supported deduction types. An empty array indicates deductions are not supported. */ + /** + * Sets [Builder.employeeDeduction] to an arbitrary JSON value. + * + * You should usually call [Builder.employeeDeduction] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun employeeDeduction(employeeDeduction: JsonField>) = apply { this.employeeDeduction = employeeDeduction.map { it.toMutableList() } } - /** Supported deduction types. An empty array indicates deductions are not supported. */ + /** + * Adds a single [EmployeeDeduction] to [Builder.employeeDeduction]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addEmployeeDeduction(employeeDeduction: EmployeeDeduction) = apply { this.employeeDeduction = - (this.employeeDeduction ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(employeeDeduction) + (this.employeeDeduction ?: JsonField.of(mutableListOf())).also { + checkKnown("employeeDeduction", it).add(employeeDeduction) } } @@ -400,22 +550,26 @@ private constructor( fun frequencies(frequencies: List) = frequencies(JsonField.of(frequencies)) - /** The list of frequencies supported by the provider for this benefit */ + /** + * Sets [Builder.frequencies] to an arbitrary JSON value. + * + * You should usually call [Builder.frequencies] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun frequencies(frequencies: JsonField>) = apply { this.frequencies = frequencies.map { it.toMutableList() } } - /** The list of frequencies supported by the provider for this benefit */ + /** + * Adds a single [BenefitFrequency] to [frequencies]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addFrequency(frequency: BenefitFrequency) = apply { frequencies = - (frequencies ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(frequency) + (frequencies ?: JsonField.of(mutableListOf())).also { + checkKnown("frequencies", it).add(frequency) } } @@ -427,15 +581,18 @@ private constructor( hsaContributionLimit(JsonField.ofNullable(hsaContributionLimit)) /** - * Whether the provider supports HSA contribution limits. Empty if this feature is not - * supported for the benefit. This array only has values for HSA benefits. + * Alias for calling [Builder.hsaContributionLimit] with + * `hsaContributionLimit.orElse(null)`. */ fun hsaContributionLimit(hsaContributionLimit: Optional>) = - hsaContributionLimit(hsaContributionLimit.orElse(null)) + hsaContributionLimit(hsaContributionLimit.getOrNull()) /** - * Whether the provider supports HSA contribution limits. Empty if this feature is not - * supported for the benefit. This array only has values for HSA benefits. + * Sets [Builder.hsaContributionLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.hsaContributionLimit] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. */ fun hsaContributionLimit(hsaContributionLimit: JsonField>) = apply { @@ -443,19 +600,14 @@ private constructor( } /** - * Whether the provider supports HSA contribution limits. Empty if this feature is not - * supported for the benefit. This array only has values for HSA benefits. + * Adds a single [HsaContributionLimit] to [Builder.hsaContributionLimit]. + * + * @throws IllegalStateException if the field was previously set to a non-list. */ fun addHsaContributionLimit(hsaContributionLimit: HsaContributionLimit) = apply { this.hsaContributionLimit = - (this.hsaContributionLimit ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(hsaContributionLimit) + (this.hsaContributionLimit ?: JsonField.of(mutableListOf())).also { + checkKnown("hsaContributionLimit", it).add(hsaContributionLimit) } } @@ -478,6 +630,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [BenefitFeature]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): BenefitFeature = BenefitFeature( annualMaximum, @@ -487,10 +644,54 @@ private constructor( (employeeDeduction ?: JsonMissing.of()).map { it.toImmutable() }, (frequencies ?: JsonMissing.of()).map { it.toImmutable() }, (hsaContributionLimit ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): BenefitFeature = apply { + if (validated) { + return@apply + } + + annualMaximum() + catchUp() + companyContribution().ifPresent { it.forEach { it?.validate() } } + description() + employeeDeduction().ifPresent { it.forEach { it?.validate() } } + frequencies().ifPresent { it.forEach { it?.validate() } } + hsaContributionLimit().ifPresent { it.forEach { it?.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (annualMaximum.asKnown().isPresent) 1 else 0) + + (if (catchUp.asKnown().isPresent) 1 else 0) + + (companyContribution.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } + ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (employeeDeduction.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } + ?: 0) + + (frequencies.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (hsaContributionLimit.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } + ?: 0) + class CompanyContribution @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -585,6 +786,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): CompanyContribution = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -691,6 +919,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EmployeeDeduction = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -798,6 +1053,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): HsaContributionLimit = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitFrequency.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitFrequency.kt index 3a3183a0..0d37a391 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitFrequency.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitFrequency.kt @@ -7,6 +7,7 @@ import com.tryfinch.api.core.Enum import com.tryfinch.api.core.JsonField import com.tryfinch.api.errors.FinchInvalidDataException +/** The frequency of the benefit deduction/contribution. */ class BenefitFrequency @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -99,6 +100,32 @@ class BenefitFrequency @JsonCreator private constructor(private val value: JsonF fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): BenefitFrequency = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitType.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitType.kt index 4f7b1a34..27b2ed15 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitType.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitType.kt @@ -193,6 +193,32 @@ class BenefitType @JsonCreator private constructor(private val value: JsonField< fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): BenefitType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitsSupport.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitsSupport.kt index 80e52ec7..b0b0c886 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitsSupport.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/BenefitsSupport.kt @@ -10,173 +10,287 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** * Each benefit type and their supported features. If the benefit type is not supported, the * property will be null */ -@NoAutoDetect class BenefitsSupport -@JsonCreator private constructor( - @JsonProperty("commuter") - @ExcludeMissing - private val commuter: JsonField = JsonMissing.of(), - @JsonProperty("custom_post_tax") - @ExcludeMissing - private val customPostTax: JsonField = JsonMissing.of(), - @JsonProperty("custom_pre_tax") - @ExcludeMissing - private val customPreTax: JsonField = JsonMissing.of(), - @JsonProperty("fsa_dependent_care") - @ExcludeMissing - private val fsaDependentCare: JsonField = JsonMissing.of(), - @JsonProperty("fsa_medical") - @ExcludeMissing - private val fsaMedical: JsonField = JsonMissing.of(), - @JsonProperty("hsa_post") - @ExcludeMissing - private val hsaPost: JsonField = JsonMissing.of(), - @JsonProperty("hsa_pre") - @ExcludeMissing - private val hsaPre: JsonField = JsonMissing.of(), - @JsonProperty("s125_dental") - @ExcludeMissing - private val s125Dental: JsonField = JsonMissing.of(), - @JsonProperty("s125_medical") - @ExcludeMissing - private val s125Medical: JsonField = JsonMissing.of(), - @JsonProperty("s125_vision") - @ExcludeMissing - private val s125Vision: JsonField = JsonMissing.of(), - @JsonProperty("simple") - @ExcludeMissing - private val simple: JsonField = JsonMissing.of(), - @JsonProperty("simple_ira") - @ExcludeMissing - private val simpleIra: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val commuter: JsonField, + private val customPostTax: JsonField, + private val customPreTax: JsonField, + private val fsaDependentCare: JsonField, + private val fsaMedical: JsonField, + private val hsaPost: JsonField, + private val hsaPre: JsonField, + private val s125Dental: JsonField, + private val s125Medical: JsonField, + private val s125Vision: JsonField, + private val simple: JsonField, + private val simpleIra: JsonField, + private val additionalProperties: MutableMap, ) { - fun commuter(): Optional = - Optional.ofNullable(commuter.getNullable("commuter")) - + @JsonCreator + private constructor( + @JsonProperty("commuter") + @ExcludeMissing + commuter: JsonField = JsonMissing.of(), + @JsonProperty("custom_post_tax") + @ExcludeMissing + customPostTax: JsonField = JsonMissing.of(), + @JsonProperty("custom_pre_tax") + @ExcludeMissing + customPreTax: JsonField = JsonMissing.of(), + @JsonProperty("fsa_dependent_care") + @ExcludeMissing + fsaDependentCare: JsonField = JsonMissing.of(), + @JsonProperty("fsa_medical") + @ExcludeMissing + fsaMedical: JsonField = JsonMissing.of(), + @JsonProperty("hsa_post") + @ExcludeMissing + hsaPost: JsonField = JsonMissing.of(), + @JsonProperty("hsa_pre") + @ExcludeMissing + hsaPre: JsonField = JsonMissing.of(), + @JsonProperty("s125_dental") + @ExcludeMissing + s125Dental: JsonField = JsonMissing.of(), + @JsonProperty("s125_medical") + @ExcludeMissing + s125Medical: JsonField = JsonMissing.of(), + @JsonProperty("s125_vision") + @ExcludeMissing + s125Vision: JsonField = JsonMissing.of(), + @JsonProperty("simple") + @ExcludeMissing + simple: JsonField = JsonMissing.of(), + @JsonProperty("simple_ira") + @ExcludeMissing + simpleIra: JsonField = JsonMissing.of(), + ) : this( + commuter, + customPostTax, + customPreTax, + fsaDependentCare, + fsaMedical, + hsaPost, + hsaPre, + s125Dental, + s125Medical, + s125Vision, + simple, + simpleIra, + mutableMapOf(), + ) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun commuter(): Optional = commuter.getOptional("commuter") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun customPostTax(): Optional = - Optional.ofNullable(customPostTax.getNullable("custom_post_tax")) + customPostTax.getOptional("custom_post_tax") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun customPreTax(): Optional = - Optional.ofNullable(customPreTax.getNullable("custom_pre_tax")) + customPreTax.getOptional("custom_pre_tax") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun fsaDependentCare(): Optional = - Optional.ofNullable(fsaDependentCare.getNullable("fsa_dependent_care")) - - fun fsaMedical(): Optional = - Optional.ofNullable(fsaMedical.getNullable("fsa_medical")) - - fun hsaPost(): Optional = - Optional.ofNullable(hsaPost.getNullable("hsa_post")) - - fun hsaPre(): Optional = - Optional.ofNullable(hsaPre.getNullable("hsa_pre")) - - fun s125Dental(): Optional = - Optional.ofNullable(s125Dental.getNullable("s125_dental")) - + fsaDependentCare.getOptional("fsa_dependent_care") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun fsaMedical(): Optional = fsaMedical.getOptional("fsa_medical") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun hsaPost(): Optional = hsaPost.getOptional("hsa_post") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun hsaPre(): Optional = hsaPre.getOptional("hsa_pre") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun s125Dental(): Optional = s125Dental.getOptional("s125_dental") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun s125Medical(): Optional = - Optional.ofNullable(s125Medical.getNullable("s125_medical")) - - fun s125Vision(): Optional = - Optional.ofNullable(s125Vision.getNullable("s125_vision")) - - fun simple(): Optional = - Optional.ofNullable(simple.getNullable("simple")) - - fun simpleIra(): Optional = - Optional.ofNullable(simpleIra.getNullable("simple_ira")) - + s125Medical.getOptional("s125_medical") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun s125Vision(): Optional = s125Vision.getOptional("s125_vision") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun simple(): Optional = simple.getOptional("simple") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun simpleIra(): Optional = simpleIra.getOptional("simple_ira") + + /** + * Returns the raw JSON value of [commuter]. + * + * Unlike [commuter], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("commuter") @ExcludeMissing fun _commuter(): JsonField = commuter + /** + * Returns the raw JSON value of [customPostTax]. + * + * Unlike [customPostTax], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("custom_post_tax") @ExcludeMissing fun _customPostTax(): JsonField = customPostTax + /** + * Returns the raw JSON value of [customPreTax]. + * + * Unlike [customPreTax], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("custom_pre_tax") @ExcludeMissing fun _customPreTax(): JsonField = customPreTax + /** + * Returns the raw JSON value of [fsaDependentCare]. + * + * Unlike [fsaDependentCare], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("fsa_dependent_care") @ExcludeMissing fun _fsaDependentCare(): JsonField = fsaDependentCare + /** + * Returns the raw JSON value of [fsaMedical]. + * + * Unlike [fsaMedical], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("fsa_medical") @ExcludeMissing fun _fsaMedical(): JsonField = fsaMedical + /** + * Returns the raw JSON value of [hsaPost]. + * + * Unlike [hsaPost], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("hsa_post") @ExcludeMissing fun _hsaPost(): JsonField = hsaPost + /** + * Returns the raw JSON value of [hsaPre]. + * + * Unlike [hsaPre], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("hsa_pre") @ExcludeMissing fun _hsaPre(): JsonField = hsaPre + /** + * Returns the raw JSON value of [s125Dental]. + * + * Unlike [s125Dental], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("s125_dental") @ExcludeMissing fun _s125Dental(): JsonField = s125Dental + /** + * Returns the raw JSON value of [s125Medical]. + * + * Unlike [s125Medical], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("s125_medical") @ExcludeMissing fun _s125Medical(): JsonField = s125Medical + /** + * Returns the raw JSON value of [s125Vision]. + * + * Unlike [s125Vision], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("s125_vision") @ExcludeMissing fun _s125Vision(): JsonField = s125Vision + /** + * Returns the raw JSON value of [simple]. + * + * Unlike [simple], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("simple") @ExcludeMissing fun _simple(): JsonField = simple + /** + * Returns the raw JSON value of [simpleIra]. + * + * Unlike [simpleIra], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("simple_ira") @ExcludeMissing fun _simpleIra(): JsonField = simpleIra + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): BenefitsSupport = apply { - if (validated) { - return@apply - } - - commuter().ifPresent { it.validate() } - customPostTax().ifPresent { it.validate() } - customPreTax().ifPresent { it.validate() } - fsaDependentCare().ifPresent { it.validate() } - fsaMedical().ifPresent { it.validate() } - hsaPost().ifPresent { it.validate() } - hsaPre().ifPresent { it.validate() } - s125Dental().ifPresent { it.validate() } - s125Medical().ifPresent { it.validate() } - s125Vision().ifPresent { it.validate() } - simple().ifPresent { it.validate() } - simpleIra().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [BenefitsSupport]. */ @JvmStatic fun builder() = Builder() } @@ -217,9 +331,17 @@ private constructor( fun commuter(commuter: BenefitFeaturesAndOperations?) = commuter(JsonField.ofNullable(commuter)) + /** Alias for calling [Builder.commuter] with `commuter.orElse(null)`. */ fun commuter(commuter: Optional) = - commuter(commuter.orElse(null)) - + commuter(commuter.getOrNull()) + + /** + * Sets [Builder.commuter] to an arbitrary JSON value. + * + * You should usually call [Builder.commuter] with a well-typed + * [BenefitFeaturesAndOperations] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun commuter(commuter: JsonField) = apply { this.commuter = commuter } @@ -227,9 +349,17 @@ private constructor( fun customPostTax(customPostTax: BenefitFeaturesAndOperations?) = customPostTax(JsonField.ofNullable(customPostTax)) + /** Alias for calling [Builder.customPostTax] with `customPostTax.orElse(null)`. */ fun customPostTax(customPostTax: Optional) = - customPostTax(customPostTax.orElse(null)) - + customPostTax(customPostTax.getOrNull()) + + /** + * Sets [Builder.customPostTax] to an arbitrary JSON value. + * + * You should usually call [Builder.customPostTax] with a well-typed + * [BenefitFeaturesAndOperations] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun customPostTax(customPostTax: JsonField) = apply { this.customPostTax = customPostTax } @@ -237,9 +367,17 @@ private constructor( fun customPreTax(customPreTax: BenefitFeaturesAndOperations?) = customPreTax(JsonField.ofNullable(customPreTax)) + /** Alias for calling [Builder.customPreTax] with `customPreTax.orElse(null)`. */ fun customPreTax(customPreTax: Optional) = - customPreTax(customPreTax.orElse(null)) - + customPreTax(customPreTax.getOrNull()) + + /** + * Sets [Builder.customPreTax] to an arbitrary JSON value. + * + * You should usually call [Builder.customPreTax] with a well-typed + * [BenefitFeaturesAndOperations] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun customPreTax(customPreTax: JsonField) = apply { this.customPreTax = customPreTax } @@ -247,9 +385,17 @@ private constructor( fun fsaDependentCare(fsaDependentCare: BenefitFeaturesAndOperations?) = fsaDependentCare(JsonField.ofNullable(fsaDependentCare)) + /** Alias for calling [Builder.fsaDependentCare] with `fsaDependentCare.orElse(null)`. */ fun fsaDependentCare(fsaDependentCare: Optional) = - fsaDependentCare(fsaDependentCare.orElse(null)) - + fsaDependentCare(fsaDependentCare.getOrNull()) + + /** + * Sets [Builder.fsaDependentCare] to an arbitrary JSON value. + * + * You should usually call [Builder.fsaDependentCare] with a well-typed + * [BenefitFeaturesAndOperations] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun fsaDependentCare(fsaDependentCare: JsonField) = apply { this.fsaDependentCare = fsaDependentCare } @@ -257,33 +403,65 @@ private constructor( fun fsaMedical(fsaMedical: BenefitFeaturesAndOperations?) = fsaMedical(JsonField.ofNullable(fsaMedical)) + /** Alias for calling [Builder.fsaMedical] with `fsaMedical.orElse(null)`. */ fun fsaMedical(fsaMedical: Optional) = - fsaMedical(fsaMedical.orElse(null)) - + fsaMedical(fsaMedical.getOrNull()) + + /** + * Sets [Builder.fsaMedical] to an arbitrary JSON value. + * + * You should usually call [Builder.fsaMedical] with a well-typed + * [BenefitFeaturesAndOperations] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun fsaMedical(fsaMedical: JsonField) = apply { this.fsaMedical = fsaMedical } fun hsaPost(hsaPost: BenefitFeaturesAndOperations?) = hsaPost(JsonField.ofNullable(hsaPost)) - fun hsaPost(hsaPost: Optional) = hsaPost(hsaPost.orElse(null)) + /** Alias for calling [Builder.hsaPost] with `hsaPost.orElse(null)`. */ + fun hsaPost(hsaPost: Optional) = hsaPost(hsaPost.getOrNull()) + /** + * Sets [Builder.hsaPost] to an arbitrary JSON value. + * + * You should usually call [Builder.hsaPost] with a well-typed + * [BenefitFeaturesAndOperations] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun hsaPost(hsaPost: JsonField) = apply { this.hsaPost = hsaPost } fun hsaPre(hsaPre: BenefitFeaturesAndOperations?) = hsaPre(JsonField.ofNullable(hsaPre)) - fun hsaPre(hsaPre: Optional) = hsaPre(hsaPre.orElse(null)) + /** Alias for calling [Builder.hsaPre] with `hsaPre.orElse(null)`. */ + fun hsaPre(hsaPre: Optional) = hsaPre(hsaPre.getOrNull()) + /** + * Sets [Builder.hsaPre] to an arbitrary JSON value. + * + * You should usually call [Builder.hsaPre] with a well-typed [BenefitFeaturesAndOperations] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun hsaPre(hsaPre: JsonField) = apply { this.hsaPre = hsaPre } fun s125Dental(s125Dental: BenefitFeaturesAndOperations?) = s125Dental(JsonField.ofNullable(s125Dental)) + /** Alias for calling [Builder.s125Dental] with `s125Dental.orElse(null)`. */ fun s125Dental(s125Dental: Optional) = - s125Dental(s125Dental.orElse(null)) - + s125Dental(s125Dental.getOrNull()) + + /** + * Sets [Builder.s125Dental] to an arbitrary JSON value. + * + * You should usually call [Builder.s125Dental] with a well-typed + * [BenefitFeaturesAndOperations] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun s125Dental(s125Dental: JsonField) = apply { this.s125Dental = s125Dental } @@ -291,9 +469,17 @@ private constructor( fun s125Medical(s125Medical: BenefitFeaturesAndOperations?) = s125Medical(JsonField.ofNullable(s125Medical)) + /** Alias for calling [Builder.s125Medical] with `s125Medical.orElse(null)`. */ fun s125Medical(s125Medical: Optional) = - s125Medical(s125Medical.orElse(null)) - + s125Medical(s125Medical.getOrNull()) + + /** + * Sets [Builder.s125Medical] to an arbitrary JSON value. + * + * You should usually call [Builder.s125Medical] with a well-typed + * [BenefitFeaturesAndOperations] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun s125Medical(s125Medical: JsonField) = apply { this.s125Medical = s125Medical } @@ -301,25 +487,49 @@ private constructor( fun s125Vision(s125Vision: BenefitFeaturesAndOperations?) = s125Vision(JsonField.ofNullable(s125Vision)) + /** Alias for calling [Builder.s125Vision] with `s125Vision.orElse(null)`. */ fun s125Vision(s125Vision: Optional) = - s125Vision(s125Vision.orElse(null)) - + s125Vision(s125Vision.getOrNull()) + + /** + * Sets [Builder.s125Vision] to an arbitrary JSON value. + * + * You should usually call [Builder.s125Vision] with a well-typed + * [BenefitFeaturesAndOperations] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun s125Vision(s125Vision: JsonField) = apply { this.s125Vision = s125Vision } fun simple(simple: BenefitFeaturesAndOperations?) = simple(JsonField.ofNullable(simple)) - fun simple(simple: Optional) = simple(simple.orElse(null)) + /** Alias for calling [Builder.simple] with `simple.orElse(null)`. */ + fun simple(simple: Optional) = simple(simple.getOrNull()) + /** + * Sets [Builder.simple] to an arbitrary JSON value. + * + * You should usually call [Builder.simple] with a well-typed [BenefitFeaturesAndOperations] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun simple(simple: JsonField) = apply { this.simple = simple } fun simpleIra(simpleIra: BenefitFeaturesAndOperations?) = simpleIra(JsonField.ofNullable(simpleIra)) + /** Alias for calling [Builder.simpleIra] with `simpleIra.orElse(null)`. */ fun simpleIra(simpleIra: Optional) = - simpleIra(simpleIra.orElse(null)) - + simpleIra(simpleIra.getOrNull()) + + /** + * Sets [Builder.simpleIra] to an arbitrary JSON value. + * + * You should usually call [Builder.simpleIra] with a well-typed + * [BenefitFeaturesAndOperations] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun simpleIra(simpleIra: JsonField) = apply { this.simpleIra = simpleIra } @@ -343,6 +553,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [BenefitsSupport]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): BenefitsSupport = BenefitsSupport( commuter, @@ -357,10 +572,60 @@ private constructor( s125Vision, simple, simpleIra, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): BenefitsSupport = apply { + if (validated) { + return@apply + } + + commuter().ifPresent { it.validate() } + customPostTax().ifPresent { it.validate() } + customPreTax().ifPresent { it.validate() } + fsaDependentCare().ifPresent { it.validate() } + fsaMedical().ifPresent { it.validate() } + hsaPost().ifPresent { it.validate() } + hsaPre().ifPresent { it.validate() } + s125Dental().ifPresent { it.validate() } + s125Medical().ifPresent { it.validate() } + s125Vision().ifPresent { it.validate() } + simple().ifPresent { it.validate() } + simpleIra().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (commuter.asKnown().getOrNull()?.validity() ?: 0) + + (customPostTax.asKnown().getOrNull()?.validity() ?: 0) + + (customPreTax.asKnown().getOrNull()?.validity() ?: 0) + + (fsaDependentCare.asKnown().getOrNull()?.validity() ?: 0) + + (fsaMedical.asKnown().getOrNull()?.validity() ?: 0) + + (hsaPost.asKnown().getOrNull()?.validity() ?: 0) + + (hsaPre.asKnown().getOrNull()?.validity() ?: 0) + + (s125Dental.asKnown().getOrNull()?.validity() ?: 0) + + (s125Medical.asKnown().getOrNull()?.validity() ?: 0) + + (s125Vision.asKnown().getOrNull()?.validity() ?: 0) + + (simple.asKnown().getOrNull()?.validity() ?: 0) + + (simpleIra.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Company.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Company.kt index 4501824b..d77d890c 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Company.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Company.kt @@ -11,135 +11,236 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class Company -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("accounts") - @ExcludeMissing - private val accounts: JsonField> = JsonMissing.of(), - @JsonProperty("departments") - @ExcludeMissing - private val departments: JsonField> = JsonMissing.of(), - @JsonProperty("ein") @ExcludeMissing private val ein: JsonField = JsonMissing.of(), - @JsonProperty("entity") - @ExcludeMissing - private val entity: JsonField = JsonMissing.of(), - @JsonProperty("legal_name") - @ExcludeMissing - private val legalName: JsonField = JsonMissing.of(), - @JsonProperty("locations") - @ExcludeMissing - private val locations: JsonField> = JsonMissing.of(), - @JsonProperty("primary_email") - @ExcludeMissing - private val primaryEmail: JsonField = JsonMissing.of(), - @JsonProperty("primary_phone_number") - @ExcludeMissing - private val primaryPhoneNumber: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val accounts: JsonField>, + private val departments: JsonField>, + private val ein: JsonField, + private val entity: JsonField, + private val legalName: JsonField, + private val locations: JsonField>, + private val primaryEmail: JsonField, + private val primaryPhoneNumber: JsonField, + private val additionalProperties: MutableMap, ) { - /** A stable Finch `id` (UUID v4) for the company. */ + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("accounts") + @ExcludeMissing + accounts: JsonField> = JsonMissing.of(), + @JsonProperty("departments") + @ExcludeMissing + departments: JsonField> = JsonMissing.of(), + @JsonProperty("ein") @ExcludeMissing ein: JsonField = JsonMissing.of(), + @JsonProperty("entity") @ExcludeMissing entity: JsonField = JsonMissing.of(), + @JsonProperty("legal_name") @ExcludeMissing legalName: JsonField = JsonMissing.of(), + @JsonProperty("locations") + @ExcludeMissing + locations: JsonField> = JsonMissing.of(), + @JsonProperty("primary_email") + @ExcludeMissing + primaryEmail: JsonField = JsonMissing.of(), + @JsonProperty("primary_phone_number") + @ExcludeMissing + primaryPhoneNumber: JsonField = JsonMissing.of(), + ) : this( + id, + accounts, + departments, + ein, + entity, + legalName, + locations, + primaryEmail, + primaryPhoneNumber, + mutableMapOf(), + ) + + /** + * A stable Finch `id` (UUID v4) for the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun id(): String = id.getRequired("id") - /** An array of bank account objects associated with the payroll/HRIS system. */ - fun accounts(): Optional> = Optional.ofNullable(accounts.getNullable("accounts")) - - /** The array of company departments. */ - fun departments(): Optional> = - Optional.ofNullable(departments.getNullable("departments")) - - /** The employer identification number. */ - fun ein(): Optional = Optional.ofNullable(ein.getNullable("ein")) - - /** The entity type object. */ - fun entity(): Optional = Optional.ofNullable(entity.getNullable("entity")) - - /** The legal name of the company. */ - fun legalName(): Optional = Optional.ofNullable(legalName.getNullable("legal_name")) - - fun locations(): Optional> = - Optional.ofNullable(locations.getNullable("locations")) - - /** The email of the main administrator on the account. */ - fun primaryEmail(): Optional = - Optional.ofNullable(primaryEmail.getNullable("primary_email")) - - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ + /** + * An array of bank account objects associated with the payroll/HRIS system. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun accounts(): Optional> = accounts.getOptional("accounts") + + /** + * The array of company departments. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun departments(): Optional> = departments.getOptional("departments") + + /** + * The employer identification number. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun ein(): Optional = ein.getOptional("ein") + + /** + * The entity type object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun entity(): Optional = entity.getOptional("entity") + + /** + * The legal name of the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun legalName(): Optional = legalName.getOptional("legal_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun locations(): Optional> = locations.getOptional("locations") + + /** + * The email of the main administrator on the account. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun primaryEmail(): Optional = primaryEmail.getOptional("primary_email") + + /** + * The phone number of the main administrator on the account. Format: `XXXXXXXXXX` + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun primaryPhoneNumber(): Optional = - Optional.ofNullable(primaryPhoneNumber.getNullable("primary_phone_number")) + primaryPhoneNumber.getOptional("primary_phone_number") - /** A stable Finch `id` (UUID v4) for the company. */ + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - /** An array of bank account objects associated with the payroll/HRIS system. */ + /** + * Returns the raw JSON value of [accounts]. + * + * Unlike [accounts], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("accounts") @ExcludeMissing fun _accounts(): JsonField> = accounts - /** The array of company departments. */ + /** + * Returns the raw JSON value of [departments]. + * + * Unlike [departments], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("departments") @ExcludeMissing fun _departments(): JsonField> = departments - /** The employer identification number. */ + /** + * Returns the raw JSON value of [ein]. + * + * Unlike [ein], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("ein") @ExcludeMissing fun _ein(): JsonField = ein - /** The entity type object. */ + /** + * Returns the raw JSON value of [entity]. + * + * Unlike [entity], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("entity") @ExcludeMissing fun _entity(): JsonField = entity - /** The legal name of the company. */ + /** + * Returns the raw JSON value of [legalName]. + * + * Unlike [legalName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("legal_name") @ExcludeMissing fun _legalName(): JsonField = legalName + /** + * Returns the raw JSON value of [locations]. + * + * Unlike [locations], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("locations") @ExcludeMissing fun _locations(): JsonField> = locations - /** The email of the main administrator on the account. */ + /** + * Returns the raw JSON value of [primaryEmail]. + * + * Unlike [primaryEmail], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("primary_email") @ExcludeMissing fun _primaryEmail(): JsonField = primaryEmail - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ + /** + * Returns the raw JSON value of [primaryPhoneNumber]. + * + * Unlike [primaryPhoneNumber], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("primary_phone_number") @ExcludeMissing fun _primaryPhoneNumber(): JsonField = primaryPhoneNumber + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Company = apply { - if (validated) { - return@apply - } - - id() - accounts().ifPresent { it.forEach { it.validate() } } - departments().ifPresent { it.forEach { it?.validate() } } - ein() - entity().ifPresent { it.validate() } - legalName() - locations().ifPresent { it.forEach { it?.validate() } } - primaryEmail() - primaryPhoneNumber() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Company]. + * + * The following fields are required: + * ```java + * .id() + * .accounts() + * .departments() + * .ein() + * .entity() + * .legalName() + * .locations() + * .primaryEmail() + * .primaryPhoneNumber() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -174,31 +275,40 @@ private constructor( /** A stable Finch `id` (UUID v4) for the company. */ fun id(id: String) = id(JsonField.of(id)) - /** A stable Finch `id` (UUID v4) for the company. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } /** An array of bank account objects associated with the payroll/HRIS system. */ fun accounts(accounts: List?) = accounts(JsonField.ofNullable(accounts)) - /** An array of bank account objects associated with the payroll/HRIS system. */ - fun accounts(accounts: Optional>) = accounts(accounts.orElse(null)) + /** Alias for calling [Builder.accounts] with `accounts.orElse(null)`. */ + fun accounts(accounts: Optional>) = accounts(accounts.getOrNull()) - /** An array of bank account objects associated with the payroll/HRIS system. */ + /** + * Sets [Builder.accounts] to an arbitrary JSON value. + * + * You should usually call [Builder.accounts] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun accounts(accounts: JsonField>) = apply { this.accounts = accounts.map { it.toMutableList() } } - /** An array of bank account objects associated with the payroll/HRIS system. */ + /** + * Adds a single [Account] to [accounts]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addAccount(account: Account) = apply { accounts = - (accounts ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(account) + (accounts ?: JsonField.of(mutableListOf())).also { + checkKnown("accounts", it).add(account) } } @@ -206,84 +316,117 @@ private constructor( fun departments(departments: List?) = departments(JsonField.ofNullable(departments)) - /** The array of company departments. */ + /** Alias for calling [Builder.departments] with `departments.orElse(null)`. */ fun departments(departments: Optional>) = - departments(departments.orElse(null)) + departments(departments.getOrNull()) - /** The array of company departments. */ + /** + * Sets [Builder.departments] to an arbitrary JSON value. + * + * You should usually call [Builder.departments] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun departments(departments: JsonField>) = apply { this.departments = departments.map { it.toMutableList() } } - /** The array of company departments. */ + /** + * Adds a single [Department] to [departments]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addDepartment(department: Department) = apply { departments = - (departments ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(department) + (departments ?: JsonField.of(mutableListOf())).also { + checkKnown("departments", it).add(department) } } /** The employer identification number. */ fun ein(ein: String?) = ein(JsonField.ofNullable(ein)) - /** The employer identification number. */ - fun ein(ein: Optional) = ein(ein.orElse(null)) + /** Alias for calling [Builder.ein] with `ein.orElse(null)`. */ + fun ein(ein: Optional) = ein(ein.getOrNull()) - /** The employer identification number. */ + /** + * Sets [Builder.ein] to an arbitrary JSON value. + * + * You should usually call [Builder.ein] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun ein(ein: JsonField) = apply { this.ein = ein } /** The entity type object. */ fun entity(entity: Entity?) = entity(JsonField.ofNullable(entity)) - /** The entity type object. */ - fun entity(entity: Optional) = entity(entity.orElse(null)) + /** Alias for calling [Builder.entity] with `entity.orElse(null)`. */ + fun entity(entity: Optional) = entity(entity.getOrNull()) - /** The entity type object. */ + /** + * Sets [Builder.entity] to an arbitrary JSON value. + * + * You should usually call [Builder.entity] with a well-typed [Entity] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun entity(entity: JsonField) = apply { this.entity = entity } /** The legal name of the company. */ fun legalName(legalName: String?) = legalName(JsonField.ofNullable(legalName)) - /** The legal name of the company. */ - fun legalName(legalName: Optional) = legalName(legalName.orElse(null)) + /** Alias for calling [Builder.legalName] with `legalName.orElse(null)`. */ + fun legalName(legalName: Optional) = legalName(legalName.getOrNull()) - /** The legal name of the company. */ + /** + * Sets [Builder.legalName] to an arbitrary JSON value. + * + * You should usually call [Builder.legalName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun legalName(legalName: JsonField) = apply { this.legalName = legalName } fun locations(locations: List?) = locations(JsonField.ofNullable(locations)) - fun locations(locations: Optional>) = locations(locations.orElse(null)) + /** Alias for calling [Builder.locations] with `locations.orElse(null)`. */ + fun locations(locations: Optional>) = locations(locations.getOrNull()) + /** + * Sets [Builder.locations] to an arbitrary JSON value. + * + * You should usually call [Builder.locations] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun locations(locations: JsonField>) = apply { this.locations = locations.map { it.toMutableList() } } + /** + * Adds a single [Location] to [locations]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addLocation(location: Location) = apply { locations = - (locations ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(location) + (locations ?: JsonField.of(mutableListOf())).also { + checkKnown("locations", it).add(location) } } /** The email of the main administrator on the account. */ fun primaryEmail(primaryEmail: String?) = primaryEmail(JsonField.ofNullable(primaryEmail)) - /** The email of the main administrator on the account. */ - fun primaryEmail(primaryEmail: Optional) = primaryEmail(primaryEmail.orElse(null)) + /** Alias for calling [Builder.primaryEmail] with `primaryEmail.orElse(null)`. */ + fun primaryEmail(primaryEmail: Optional) = primaryEmail(primaryEmail.getOrNull()) - /** The email of the main administrator on the account. */ + /** + * Sets [Builder.primaryEmail] to an arbitrary JSON value. + * + * You should usually call [Builder.primaryEmail] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun primaryEmail(primaryEmail: JsonField) = apply { this.primaryEmail = primaryEmail } @@ -292,11 +435,19 @@ private constructor( fun primaryPhoneNumber(primaryPhoneNumber: String?) = primaryPhoneNumber(JsonField.ofNullable(primaryPhoneNumber)) - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ + /** + * Alias for calling [Builder.primaryPhoneNumber] with `primaryPhoneNumber.orElse(null)`. + */ fun primaryPhoneNumber(primaryPhoneNumber: Optional) = - primaryPhoneNumber(primaryPhoneNumber.orElse(null)) + primaryPhoneNumber(primaryPhoneNumber.getOrNull()) - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ + /** + * Sets [Builder.primaryPhoneNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.primaryPhoneNumber] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun primaryPhoneNumber(primaryPhoneNumber: JsonField) = apply { this.primaryPhoneNumber = primaryPhoneNumber } @@ -320,6 +471,26 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Company]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .accounts() + * .departments() + * .ein() + * .entity() + * .legalName() + * .locations() + * .primaryEmail() + * .primaryPhoneNumber() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Company = Company( checkRequired("id", id), @@ -331,105 +502,193 @@ private constructor( checkRequired("locations", locations).map { it.toImmutable() }, checkRequired("primaryEmail", primaryEmail), checkRequired("primaryPhoneNumber", primaryPhoneNumber), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Company = apply { + if (validated) { + return@apply + } + + id() + accounts().ifPresent { it.forEach { it.validate() } } + departments().ifPresent { it.forEach { it?.validate() } } + ein() + entity().ifPresent { it.validate() } + legalName() + locations().ifPresent { it.forEach { it?.validate() } } + primaryEmail() + primaryPhoneNumber() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (accounts.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (departments.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (ein.asKnown().isPresent) 1 else 0) + + (entity.asKnown().getOrNull()?.validity() ?: 0) + + (if (legalName.asKnown().isPresent) 1 else 0) + + (locations.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (primaryEmail.asKnown().isPresent) 1 else 0) + + (if (primaryPhoneNumber.asKnown().isPresent) 1 else 0) + class Account - @JsonCreator private constructor( - @JsonProperty("account_name") - @ExcludeMissing - private val accountName: JsonField = JsonMissing.of(), - @JsonProperty("account_number") - @ExcludeMissing - private val accountNumber: JsonField = JsonMissing.of(), - @JsonProperty("account_type") - @ExcludeMissing - private val accountType: JsonField = JsonMissing.of(), - @JsonProperty("institution_name") - @ExcludeMissing - private val institutionName: JsonField = JsonMissing.of(), - @JsonProperty("routing_number") - @ExcludeMissing - private val routingNumber: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val accountName: JsonField, + private val accountNumber: JsonField, + private val accountType: JsonField, + private val institutionName: JsonField, + private val routingNumber: JsonField, + private val additionalProperties: MutableMap, ) { - /** The name of the bank associated in the payroll/HRIS system. */ - fun accountName(): Optional = - Optional.ofNullable(accountName.getNullable("account_name")) + @JsonCreator + private constructor( + @JsonProperty("account_name") + @ExcludeMissing + accountName: JsonField = JsonMissing.of(), + @JsonProperty("account_number") + @ExcludeMissing + accountNumber: JsonField = JsonMissing.of(), + @JsonProperty("account_type") + @ExcludeMissing + accountType: JsonField = JsonMissing.of(), + @JsonProperty("institution_name") + @ExcludeMissing + institutionName: JsonField = JsonMissing.of(), + @JsonProperty("routing_number") + @ExcludeMissing + routingNumber: JsonField = JsonMissing.of(), + ) : this( + accountName, + accountNumber, + accountType, + institutionName, + routingNumber, + mutableMapOf(), + ) - /** 10-12 digit number to specify the bank account */ - fun accountNumber(): Optional = - Optional.ofNullable(accountNumber.getNullable("account_number")) + /** + * The name of the bank associated in the payroll/HRIS system. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun accountName(): Optional = accountName.getOptional("account_name") - /** The type of bank account. */ - fun accountType(): Optional = - Optional.ofNullable(accountType.getNullable("account_type")) + /** + * 10-12 digit number to specify the bank account + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun accountNumber(): Optional = accountNumber.getOptional("account_number") - /** Name of the banking institution. */ - fun institutionName(): Optional = - Optional.ofNullable(institutionName.getNullable("institution_name")) + /** + * The type of bank account. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun accountType(): Optional = accountType.getOptional("account_type") + + /** + * Name of the banking institution. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun institutionName(): Optional = institutionName.getOptional("institution_name") /** * A nine-digit code that's based on the U.S. Bank location where your account was opened. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun routingNumber(): Optional = - Optional.ofNullable(routingNumber.getNullable("routing_number")) + fun routingNumber(): Optional = routingNumber.getOptional("routing_number") - /** The name of the bank associated in the payroll/HRIS system. */ + /** + * Returns the raw JSON value of [accountName]. + * + * Unlike [accountName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("account_name") @ExcludeMissing fun _accountName(): JsonField = accountName - /** 10-12 digit number to specify the bank account */ + /** + * Returns the raw JSON value of [accountNumber]. + * + * Unlike [accountNumber], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("account_number") @ExcludeMissing fun _accountNumber(): JsonField = accountNumber - /** The type of bank account. */ + /** + * Returns the raw JSON value of [accountType]. + * + * Unlike [accountType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("account_type") @ExcludeMissing fun _accountType(): JsonField = accountType - /** Name of the banking institution. */ + /** + * Returns the raw JSON value of [institutionName]. + * + * Unlike [institutionName], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("institution_name") @ExcludeMissing fun _institutionName(): JsonField = institutionName /** - * A nine-digit code that's based on the U.S. Bank location where your account was opened. + * Returns the raw JSON value of [routingNumber]. + * + * Unlike [routingNumber], this method doesn't throw if the JSON field has an unexpected + * type. */ @JsonProperty("routing_number") @ExcludeMissing fun _routingNumber(): JsonField = routingNumber + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Account = apply { - if (validated) { - return@apply - } - - accountName() - accountNumber() - accountType() - institutionName() - routingNumber() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Account]. */ @JvmStatic fun builder() = Builder() } @@ -456,10 +715,16 @@ private constructor( /** The name of the bank associated in the payroll/HRIS system. */ fun accountName(accountName: String?) = accountName(JsonField.ofNullable(accountName)) - /** The name of the bank associated in the payroll/HRIS system. */ - fun accountName(accountName: Optional) = accountName(accountName.orElse(null)) + /** Alias for calling [Builder.accountName] with `accountName.orElse(null)`. */ + fun accountName(accountName: Optional) = accountName(accountName.getOrNull()) - /** The name of the bank associated in the payroll/HRIS system. */ + /** + * Sets [Builder.accountName] to an arbitrary JSON value. + * + * You should usually call [Builder.accountName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun accountName(accountName: JsonField) = apply { this.accountName = accountName } @@ -468,11 +733,17 @@ private constructor( fun accountNumber(accountNumber: String?) = accountNumber(JsonField.ofNullable(accountNumber)) - /** 10-12 digit number to specify the bank account */ + /** Alias for calling [Builder.accountNumber] with `accountNumber.orElse(null)`. */ fun accountNumber(accountNumber: Optional) = - accountNumber(accountNumber.orElse(null)) + accountNumber(accountNumber.getOrNull()) - /** 10-12 digit number to specify the bank account */ + /** + * Sets [Builder.accountNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.accountNumber] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun accountNumber(accountNumber: JsonField) = apply { this.accountNumber = accountNumber } @@ -481,11 +752,17 @@ private constructor( fun accountType(accountType: AccountType?) = accountType(JsonField.ofNullable(accountType)) - /** The type of bank account. */ + /** Alias for calling [Builder.accountType] with `accountType.orElse(null)`. */ fun accountType(accountType: Optional) = - accountType(accountType.orElse(null)) + accountType(accountType.getOrNull()) - /** The type of bank account. */ + /** + * Sets [Builder.accountType] to an arbitrary JSON value. + * + * You should usually call [Builder.accountType] with a well-typed [AccountType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun accountType(accountType: JsonField) = apply { this.accountType = accountType } @@ -494,11 +771,17 @@ private constructor( fun institutionName(institutionName: String?) = institutionName(JsonField.ofNullable(institutionName)) - /** Name of the banking institution. */ + /** Alias for calling [Builder.institutionName] with `institutionName.orElse(null)`. */ fun institutionName(institutionName: Optional) = - institutionName(institutionName.orElse(null)) + institutionName(institutionName.getOrNull()) - /** Name of the banking institution. */ + /** + * Sets [Builder.institutionName] to an arbitrary JSON value. + * + * You should usually call [Builder.institutionName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun institutionName(institutionName: JsonField) = apply { this.institutionName = institutionName } @@ -510,16 +793,16 @@ private constructor( fun routingNumber(routingNumber: String?) = routingNumber(JsonField.ofNullable(routingNumber)) - /** - * A nine-digit code that's based on the U.S. Bank location where your account was - * opened. - */ + /** Alias for calling [Builder.routingNumber] with `routingNumber.orElse(null)`. */ fun routingNumber(routingNumber: Optional) = - routingNumber(routingNumber.orElse(null)) + routingNumber(routingNumber.getOrNull()) /** - * A nine-digit code that's based on the U.S. Bank location where your account was - * opened. + * Sets [Builder.routingNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.routingNumber] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun routingNumber(routingNumber: JsonField) = apply { this.routingNumber = routingNumber @@ -544,6 +827,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Account]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Account = Account( accountName, @@ -551,10 +839,47 @@ private constructor( accountType, institutionName, routingNumber, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Account = apply { + if (validated) { + return@apply + } + + accountName() + accountNumber() + accountType().ifPresent { it.validate() } + institutionName() + routingNumber() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountName.asKnown().isPresent) 1 else 0) + + (if (accountNumber.asKnown().isPresent) 1 else 0) + + (accountType.asKnown().getOrNull()?.validity() ?: 0) + + (if (institutionName.asKnown().isPresent) 1 else 0) + + (if (routingNumber.asKnown().isPresent) 1 else 0) + /** The type of bank account. */ class AccountType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -647,6 +972,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): AccountType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -678,52 +1030,64 @@ private constructor( "Account{accountName=$accountName, accountNumber=$accountNumber, accountType=$accountType, institutionName=$institutionName, routingNumber=$routingNumber, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Department - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("parent") - @ExcludeMissing - private val parent: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val parent: JsonField, + private val additionalProperties: MutableMap, ) { - /** The department name. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("parent") @ExcludeMissing parent: JsonField = JsonMissing.of(), + ) : this(name, parent, mutableMapOf()) - /** The parent department, if present. */ - fun parent(): Optional = Optional.ofNullable(parent.getNullable("parent")) + /** + * The department name. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * The parent department, if present. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun parent(): Optional = parent.getOptional("parent") - /** The department name. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** The parent department, if present. */ + /** + * Returns the raw JSON value of [parent]. + * + * Unlike [parent], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("parent") @ExcludeMissing fun _parent(): JsonField = parent + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Department = apply { - if (validated) { - return@apply - } - - name() - parent().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Department]. */ @JvmStatic fun builder() = Builder() } @@ -744,19 +1108,31 @@ private constructor( /** The department name. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The department name. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The department name. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } /** The parent department, if present. */ fun parent(parent: Parent?) = parent(JsonField.ofNullable(parent)) - /** The parent department, if present. */ - fun parent(parent: Optional) = parent(parent.orElse(null)) + /** Alias for calling [Builder.parent] with `parent.orElse(null)`. */ + fun parent(parent: Optional) = parent(parent.getOrNull()) - /** The parent department, if present. */ + /** + * Sets [Builder.parent] to an arbitrary JSON value. + * + * You should usually call [Builder.parent] with a well-typed [Parent] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun parent(parent: JsonField) = apply { this.parent = parent } fun additionalProperties(additionalProperties: Map) = apply { @@ -778,46 +1154,87 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Department = Department(name, parent, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Department]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Department = Department(name, parent, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Department = apply { + if (validated) { + return@apply + } + + name() + parent().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (parent.asKnown().getOrNull()?.validity() ?: 0) + /** The parent department, if present. */ - @NoAutoDetect class Parent - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - /** The parent department's name. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) - /** The parent department's name. */ + /** + * The parent department's name. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Parent = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Parent]. */ @JvmStatic fun builder() = Builder() } @@ -836,10 +1253,16 @@ private constructor( /** The parent department's name. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The parent department's name. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The parent department's name. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = apply { @@ -864,9 +1287,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Parent = Parent(name, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Parent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Parent = Parent(name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Parent = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -904,50 +1359,64 @@ private constructor( } /** The entity type object. */ - @NoAutoDetect class Entity - @JsonCreator private constructor( - @JsonProperty("subtype") - @ExcludeMissing - private val subtype: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val subtype: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The tax payer subtype of the company. */ - fun subtype(): Optional = Optional.ofNullable(subtype.getNullable("subtype")) + @JsonCreator + private constructor( + @JsonProperty("subtype") @ExcludeMissing subtype: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(subtype, type, mutableMapOf()) - /** The tax payer type of the company. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The tax payer subtype of the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun subtype(): Optional = subtype.getOptional("subtype") - /** The tax payer subtype of the company. */ + /** + * The tax payer type of the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [subtype]. + * + * Unlike [subtype], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype - /** The tax payer type of the company. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Entity = apply { - if (validated) { - return@apply - } - - subtype() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Entity]. */ @JvmStatic fun builder() = Builder() } @@ -968,19 +1437,31 @@ private constructor( /** The tax payer subtype of the company. */ fun subtype(subtype: Subtype?) = subtype(JsonField.ofNullable(subtype)) - /** The tax payer subtype of the company. */ - fun subtype(subtype: Optional) = subtype(subtype.orElse(null)) + /** Alias for calling [Builder.subtype] with `subtype.orElse(null)`. */ + fun subtype(subtype: Optional) = subtype(subtype.getOrNull()) - /** The tax payer subtype of the company. */ + /** + * Sets [Builder.subtype] to an arbitrary JSON value. + * + * You should usually call [Builder.subtype] with a well-typed [Subtype] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun subtype(subtype: JsonField) = apply { this.subtype = subtype } /** The tax payer type of the company. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** The tax payer type of the company. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** The tax payer type of the company. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -1002,9 +1483,45 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Entity = Entity(subtype, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Entity]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Entity = Entity(subtype, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Entity = apply { + if (validated) { + return@apply + } + + subtype().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (subtype.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + /** The tax payer subtype of the company. */ class Subtype @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1102,6 +1619,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Subtype = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1233,6 +1777,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CompanyBenefit.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CompanyBenefit.kt index 9f519ebf..bc621dbe 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CompanyBenefit.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CompanyBenefit.kt @@ -10,76 +10,119 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class CompanyBenefit -@JsonCreator private constructor( - @JsonProperty("benefit_id") - @ExcludeMissing - private val benefitId: JsonField = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("frequency") - @ExcludeMissing - private val frequency: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val benefitId: JsonField, + private val description: JsonField, + private val frequency: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("benefit_id") @ExcludeMissing benefitId: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("frequency") + @ExcludeMissing + frequency: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(benefitId, description, frequency, type, mutableMapOf()) + + /** + * The id of the benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun benefitId(): String = benefitId.getRequired("benefit_id") - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - fun frequency(): Optional = - Optional.ofNullable(frequency.getNullable("frequency")) - - /** Type of benefit. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * The frequency of the benefit deduction/contribution. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun frequency(): Optional = frequency.getOptional("frequency") + + /** + * Type of benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [benefitId]. + * + * Unlike [benefitId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("benefit_id") @ExcludeMissing fun _benefitId(): JsonField = benefitId + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description + /** + * Returns the raw JSON value of [frequency]. + * + * Unlike [frequency], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("frequency") @ExcludeMissing fun _frequency(): JsonField = frequency - /** Type of benefit. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): CompanyBenefit = apply { - if (validated) { - return@apply - } - - benefitId() - description() - frequency() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [CompanyBenefit]. + * + * The following fields are required: + * ```java + * .benefitId() + * .description() + * .frequency() + * .type() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -101,29 +144,60 @@ private constructor( additionalProperties = companyBenefit.additionalProperties.toMutableMap() } + /** The id of the benefit. */ fun benefitId(benefitId: String) = benefitId(JsonField.of(benefitId)) + /** + * Sets [Builder.benefitId] to an arbitrary JSON value. + * + * You should usually call [Builder.benefitId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun benefitId(benefitId: JsonField) = apply { this.benefitId = benefitId } fun description(description: String?) = description(JsonField.ofNullable(description)) - fun description(description: Optional) = description(description.orElse(null)) + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun description(description: JsonField) = apply { this.description = description } + /** The frequency of the benefit deduction/contribution. */ fun frequency(frequency: BenefitFrequency?) = frequency(JsonField.ofNullable(frequency)) - fun frequency(frequency: Optional) = frequency(frequency.orElse(null)) + /** Alias for calling [Builder.frequency] with `frequency.orElse(null)`. */ + fun frequency(frequency: Optional) = frequency(frequency.getOrNull()) + /** + * Sets [Builder.frequency] to an arbitrary JSON value. + * + * You should usually call [Builder.frequency] with a well-typed [BenefitFrequency] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun frequency(frequency: JsonField) = apply { this.frequency = frequency } /** Type of benefit. */ fun type(type: BenefitType?) = type(JsonField.ofNullable(type)) - /** Type of benefit. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** Type of benefit. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [BenefitType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -145,16 +219,65 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [CompanyBenefit]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .benefitId() + * .description() + * .frequency() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): CompanyBenefit = CompanyBenefit( checkRequired("benefitId", benefitId), checkRequired("description", description), checkRequired("frequency", frequency), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): CompanyBenefit = apply { + if (validated) { + return@apply + } + + benefitId() + description() + frequency().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (benefitId.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (frequency.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CompanyEvent.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CompanyEvent.kt index 160468eb..ce97497c 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CompanyEvent.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CompanyEvent.kt @@ -11,57 +11,86 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class CompanyEvent -@JsonCreator private constructor( - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("data") @ExcludeMissing private val data: JsonField = JsonMissing.of(), - @JsonProperty("event_type") - @ExcludeMissing - private val eventType: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accountId: JsonField, + private val companyId: JsonField, + private val connectionId: JsonField, + private val data: JsonField, + private val eventType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("event_type") + @ExcludeMissing + eventType: JsonField = JsonMissing.of(), + ) : this(accountId, companyId, connectionId, data, eventType, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder() + .accountId(accountId) + .companyId(companyId) + .connectionId(connectionId) + .build() + /** * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") /** * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") - /** Unique Finch ID of the connection associated with the webhook event. */ - fun connectionId(): Optional = - Optional.ofNullable(connectionId.getNullable("connection_id")) + /** + * Unique Finch ID of the connection associated with the webhook event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun connectionId(): Optional = connectionId.getOptional("connection_id") - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") - fun eventType(): Optional = Optional.ofNullable(eventType.getNullable("event_type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun eventType(): Optional = eventType.getOptional("event_type") /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("account_id") @@ -69,53 +98,61 @@ private constructor( fun _accountId(): JsonField = accountId /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [eventType]. + * + * Unlike [eventType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("event_type") @ExcludeMissing fun _eventType(): JsonField = eventType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBaseWebhookEvent(): BaseWebhookEvent = - BaseWebhookEvent.builder() - .accountId(accountId) - .companyId(companyId) - .connectionId(connectionId) - .build() - - private var validated: Boolean = false - - fun validate(): CompanyEvent = apply { - if (validated) { - return@apply - } - - accountId() - companyId() - connectionId() - data().ifPresent { it.validate() } - eventType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [CompanyEvent]. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -147,8 +184,11 @@ private constructor( fun accountId(accountId: String) = accountId(JsonField.of(accountId)) /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } @@ -161,8 +201,11 @@ private constructor( fun companyId(companyId: String) = companyId(JsonField.of(companyId)) /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } @@ -170,19 +213,39 @@ private constructor( /** Unique Finch ID of the connection associated with the webhook event. */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } fun data(data: Data?) = data(JsonField.ofNullable(data)) - fun data(data: Optional) = data(data.orElse(null)) + /** Alias for calling [Builder.data] with `data.orElse(null)`. */ + fun data(data: Optional) = data(data.getOrNull()) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun eventType(eventType: EventType) = eventType(JsonField.of(eventType)) + /** + * Sets [Builder.eventType] to an arbitrary JSON value. + * + * You should usually call [Builder.eventType] with a well-typed [EventType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun eventType(eventType: JsonField) = apply { this.eventType = eventType } fun additionalProperties(additionalProperties: Map) = apply { @@ -204,6 +267,19 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [CompanyEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): CompanyEvent = CompanyEvent( checkRequired("accountId", accountId), @@ -211,36 +287,62 @@ private constructor( connectionId, data, eventType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): CompanyEvent = apply { + if (validated) { + return@apply + } + + accountId() + companyId() + connectionId() + data().ifPresent { it.validate() } + eventType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountId.asKnown().isPresent) 1 else 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (eventType.asKnown().getOrNull()?.validity() ?: 0) + class Data @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): Data = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Data]. */ @JvmStatic fun builder() = Builder() } @@ -273,9 +375,42 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Data = Data(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -373,6 +508,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EventType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CompanyUpdateResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CompanyUpdateResponse.kt index 6e276c55..802688bc 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CompanyUpdateResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CompanyUpdateResponse.kt @@ -11,127 +11,217 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class CompanyUpdateResponse -@JsonCreator private constructor( - @JsonProperty("accounts") - @ExcludeMissing - private val accounts: JsonField> = JsonMissing.of(), - @JsonProperty("departments") - @ExcludeMissing - private val departments: JsonField> = JsonMissing.of(), - @JsonProperty("ein") @ExcludeMissing private val ein: JsonField = JsonMissing.of(), - @JsonProperty("entity") - @ExcludeMissing - private val entity: JsonField = JsonMissing.of(), - @JsonProperty("legal_name") - @ExcludeMissing - private val legalName: JsonField = JsonMissing.of(), - @JsonProperty("locations") - @ExcludeMissing - private val locations: JsonField> = JsonMissing.of(), - @JsonProperty("primary_email") - @ExcludeMissing - private val primaryEmail: JsonField = JsonMissing.of(), - @JsonProperty("primary_phone_number") - @ExcludeMissing - private val primaryPhoneNumber: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accounts: JsonField>, + private val departments: JsonField>, + private val ein: JsonField, + private val entity: JsonField, + private val legalName: JsonField, + private val locations: JsonField>, + private val primaryEmail: JsonField, + private val primaryPhoneNumber: JsonField, + private val additionalProperties: MutableMap, ) { - /** An array of bank account objects associated with the payroll/HRIS system. */ - fun accounts(): Optional> = Optional.ofNullable(accounts.getNullable("accounts")) - - /** The array of company departments. */ - fun departments(): Optional> = - Optional.ofNullable(departments.getNullable("departments")) - - /** The employer identification number. */ - fun ein(): Optional = Optional.ofNullable(ein.getNullable("ein")) - - /** The entity type object. */ - fun entity(): Optional = Optional.ofNullable(entity.getNullable("entity")) - - /** The legal name of the company. */ - fun legalName(): Optional = Optional.ofNullable(legalName.getNullable("legal_name")) - - fun locations(): Optional> = - Optional.ofNullable(locations.getNullable("locations")) - - /** The email of the main administrator on the account. */ - fun primaryEmail(): Optional = - Optional.ofNullable(primaryEmail.getNullable("primary_email")) - - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ + @JsonCreator + private constructor( + @JsonProperty("accounts") + @ExcludeMissing + accounts: JsonField> = JsonMissing.of(), + @JsonProperty("departments") + @ExcludeMissing + departments: JsonField> = JsonMissing.of(), + @JsonProperty("ein") @ExcludeMissing ein: JsonField = JsonMissing.of(), + @JsonProperty("entity") @ExcludeMissing entity: JsonField = JsonMissing.of(), + @JsonProperty("legal_name") @ExcludeMissing legalName: JsonField = JsonMissing.of(), + @JsonProperty("locations") + @ExcludeMissing + locations: JsonField> = JsonMissing.of(), + @JsonProperty("primary_email") + @ExcludeMissing + primaryEmail: JsonField = JsonMissing.of(), + @JsonProperty("primary_phone_number") + @ExcludeMissing + primaryPhoneNumber: JsonField = JsonMissing.of(), + ) : this( + accounts, + departments, + ein, + entity, + legalName, + locations, + primaryEmail, + primaryPhoneNumber, + mutableMapOf(), + ) + + /** + * An array of bank account objects associated with the payroll/HRIS system. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun accounts(): Optional> = accounts.getOptional("accounts") + + /** + * The array of company departments. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun departments(): Optional> = departments.getOptional("departments") + + /** + * The employer identification number. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun ein(): Optional = ein.getOptional("ein") + + /** + * The entity type object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun entity(): Optional = entity.getOptional("entity") + + /** + * The legal name of the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun legalName(): Optional = legalName.getOptional("legal_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun locations(): Optional> = locations.getOptional("locations") + + /** + * The email of the main administrator on the account. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun primaryEmail(): Optional = primaryEmail.getOptional("primary_email") + + /** + * The phone number of the main administrator on the account. Format: `XXXXXXXXXX` + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun primaryPhoneNumber(): Optional = - Optional.ofNullable(primaryPhoneNumber.getNullable("primary_phone_number")) + primaryPhoneNumber.getOptional("primary_phone_number") - /** An array of bank account objects associated with the payroll/HRIS system. */ + /** + * Returns the raw JSON value of [accounts]. + * + * Unlike [accounts], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("accounts") @ExcludeMissing fun _accounts(): JsonField> = accounts - /** The array of company departments. */ + /** + * Returns the raw JSON value of [departments]. + * + * Unlike [departments], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("departments") @ExcludeMissing fun _departments(): JsonField> = departments - /** The employer identification number. */ + /** + * Returns the raw JSON value of [ein]. + * + * Unlike [ein], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("ein") @ExcludeMissing fun _ein(): JsonField = ein - /** The entity type object. */ + /** + * Returns the raw JSON value of [entity]. + * + * Unlike [entity], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("entity") @ExcludeMissing fun _entity(): JsonField = entity - /** The legal name of the company. */ + /** + * Returns the raw JSON value of [legalName]. + * + * Unlike [legalName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("legal_name") @ExcludeMissing fun _legalName(): JsonField = legalName + /** + * Returns the raw JSON value of [locations]. + * + * Unlike [locations], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("locations") @ExcludeMissing fun _locations(): JsonField> = locations - /** The email of the main administrator on the account. */ + /** + * Returns the raw JSON value of [primaryEmail]. + * + * Unlike [primaryEmail], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("primary_email") @ExcludeMissing fun _primaryEmail(): JsonField = primaryEmail - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ + /** + * Returns the raw JSON value of [primaryPhoneNumber]. + * + * Unlike [primaryPhoneNumber], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("primary_phone_number") @ExcludeMissing fun _primaryPhoneNumber(): JsonField = primaryPhoneNumber + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): CompanyUpdateResponse = apply { - if (validated) { - return@apply - } - - accounts().ifPresent { it.forEach { it.validate() } } - departments().ifPresent { it.forEach { it?.validate() } } - ein() - entity().ifPresent { it.validate() } - legalName() - locations().ifPresent { it.forEach { it?.validate() } } - primaryEmail() - primaryPhoneNumber() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [CompanyUpdateResponse]. + * + * The following fields are required: + * ```java + * .accounts() + * .departments() + * .ein() + * .entity() + * .legalName() + * .locations() + * .primaryEmail() + * .primaryPhoneNumber() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -164,25 +254,29 @@ private constructor( /** An array of bank account objects associated with the payroll/HRIS system. */ fun accounts(accounts: List?) = accounts(JsonField.ofNullable(accounts)) - /** An array of bank account objects associated with the payroll/HRIS system. */ - fun accounts(accounts: Optional>) = accounts(accounts.orElse(null)) + /** Alias for calling [Builder.accounts] with `accounts.orElse(null)`. */ + fun accounts(accounts: Optional>) = accounts(accounts.getOrNull()) - /** An array of bank account objects associated with the payroll/HRIS system. */ + /** + * Sets [Builder.accounts] to an arbitrary JSON value. + * + * You should usually call [Builder.accounts] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun accounts(accounts: JsonField>) = apply { this.accounts = accounts.map { it.toMutableList() } } - /** An array of bank account objects associated with the payroll/HRIS system. */ + /** + * Adds a single [Account] to [accounts]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addAccount(account: Account) = apply { accounts = - (accounts ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(account) + (accounts ?: JsonField.of(mutableListOf())).also { + checkKnown("accounts", it).add(account) } } @@ -190,84 +284,117 @@ private constructor( fun departments(departments: List?) = departments(JsonField.ofNullable(departments)) - /** The array of company departments. */ + /** Alias for calling [Builder.departments] with `departments.orElse(null)`. */ fun departments(departments: Optional>) = - departments(departments.orElse(null)) + departments(departments.getOrNull()) - /** The array of company departments. */ + /** + * Sets [Builder.departments] to an arbitrary JSON value. + * + * You should usually call [Builder.departments] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun departments(departments: JsonField>) = apply { this.departments = departments.map { it.toMutableList() } } - /** The array of company departments. */ + /** + * Adds a single [Department] to [departments]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addDepartment(department: Department) = apply { departments = - (departments ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(department) + (departments ?: JsonField.of(mutableListOf())).also { + checkKnown("departments", it).add(department) } } /** The employer identification number. */ fun ein(ein: String?) = ein(JsonField.ofNullable(ein)) - /** The employer identification number. */ - fun ein(ein: Optional) = ein(ein.orElse(null)) + /** Alias for calling [Builder.ein] with `ein.orElse(null)`. */ + fun ein(ein: Optional) = ein(ein.getOrNull()) - /** The employer identification number. */ + /** + * Sets [Builder.ein] to an arbitrary JSON value. + * + * You should usually call [Builder.ein] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun ein(ein: JsonField) = apply { this.ein = ein } /** The entity type object. */ fun entity(entity: Entity?) = entity(JsonField.ofNullable(entity)) - /** The entity type object. */ - fun entity(entity: Optional) = entity(entity.orElse(null)) + /** Alias for calling [Builder.entity] with `entity.orElse(null)`. */ + fun entity(entity: Optional) = entity(entity.getOrNull()) - /** The entity type object. */ + /** + * Sets [Builder.entity] to an arbitrary JSON value. + * + * You should usually call [Builder.entity] with a well-typed [Entity] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun entity(entity: JsonField) = apply { this.entity = entity } /** The legal name of the company. */ fun legalName(legalName: String?) = legalName(JsonField.ofNullable(legalName)) - /** The legal name of the company. */ - fun legalName(legalName: Optional) = legalName(legalName.orElse(null)) + /** Alias for calling [Builder.legalName] with `legalName.orElse(null)`. */ + fun legalName(legalName: Optional) = legalName(legalName.getOrNull()) - /** The legal name of the company. */ + /** + * Sets [Builder.legalName] to an arbitrary JSON value. + * + * You should usually call [Builder.legalName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun legalName(legalName: JsonField) = apply { this.legalName = legalName } fun locations(locations: List?) = locations(JsonField.ofNullable(locations)) - fun locations(locations: Optional>) = locations(locations.orElse(null)) + /** Alias for calling [Builder.locations] with `locations.orElse(null)`. */ + fun locations(locations: Optional>) = locations(locations.getOrNull()) + /** + * Sets [Builder.locations] to an arbitrary JSON value. + * + * You should usually call [Builder.locations] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun locations(locations: JsonField>) = apply { this.locations = locations.map { it.toMutableList() } } + /** + * Adds a single [Location] to [locations]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addLocation(location: Location) = apply { locations = - (locations ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(location) + (locations ?: JsonField.of(mutableListOf())).also { + checkKnown("locations", it).add(location) } } /** The email of the main administrator on the account. */ fun primaryEmail(primaryEmail: String?) = primaryEmail(JsonField.ofNullable(primaryEmail)) - /** The email of the main administrator on the account. */ - fun primaryEmail(primaryEmail: Optional) = primaryEmail(primaryEmail.orElse(null)) + /** Alias for calling [Builder.primaryEmail] with `primaryEmail.orElse(null)`. */ + fun primaryEmail(primaryEmail: Optional) = primaryEmail(primaryEmail.getOrNull()) - /** The email of the main administrator on the account. */ + /** + * Sets [Builder.primaryEmail] to an arbitrary JSON value. + * + * You should usually call [Builder.primaryEmail] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun primaryEmail(primaryEmail: JsonField) = apply { this.primaryEmail = primaryEmail } @@ -276,11 +403,19 @@ private constructor( fun primaryPhoneNumber(primaryPhoneNumber: String?) = primaryPhoneNumber(JsonField.ofNullable(primaryPhoneNumber)) - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ + /** + * Alias for calling [Builder.primaryPhoneNumber] with `primaryPhoneNumber.orElse(null)`. + */ fun primaryPhoneNumber(primaryPhoneNumber: Optional) = - primaryPhoneNumber(primaryPhoneNumber.orElse(null)) + primaryPhoneNumber(primaryPhoneNumber.getOrNull()) - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ + /** + * Sets [Builder.primaryPhoneNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.primaryPhoneNumber] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun primaryPhoneNumber(primaryPhoneNumber: JsonField) = apply { this.primaryPhoneNumber = primaryPhoneNumber } @@ -304,6 +439,25 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [CompanyUpdateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accounts() + * .departments() + * .ein() + * .entity() + * .legalName() + * .locations() + * .primaryEmail() + * .primaryPhoneNumber() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): CompanyUpdateResponse = CompanyUpdateResponse( checkRequired("accounts", accounts).map { it.toImmutable() }, @@ -314,105 +468,191 @@ private constructor( checkRequired("locations", locations).map { it.toImmutable() }, checkRequired("primaryEmail", primaryEmail), checkRequired("primaryPhoneNumber", primaryPhoneNumber), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): CompanyUpdateResponse = apply { + if (validated) { + return@apply + } + + accounts().ifPresent { it.forEach { it.validate() } } + departments().ifPresent { it.forEach { it?.validate() } } + ein() + entity().ifPresent { it.validate() } + legalName() + locations().ifPresent { it.forEach { it?.validate() } } + primaryEmail() + primaryPhoneNumber() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (accounts.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (departments.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (ein.asKnown().isPresent) 1 else 0) + + (entity.asKnown().getOrNull()?.validity() ?: 0) + + (if (legalName.asKnown().isPresent) 1 else 0) + + (locations.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (primaryEmail.asKnown().isPresent) 1 else 0) + + (if (primaryPhoneNumber.asKnown().isPresent) 1 else 0) + class Account - @JsonCreator private constructor( - @JsonProperty("account_name") - @ExcludeMissing - private val accountName: JsonField = JsonMissing.of(), - @JsonProperty("account_number") - @ExcludeMissing - private val accountNumber: JsonField = JsonMissing.of(), - @JsonProperty("account_type") - @ExcludeMissing - private val accountType: JsonField = JsonMissing.of(), - @JsonProperty("institution_name") - @ExcludeMissing - private val institutionName: JsonField = JsonMissing.of(), - @JsonProperty("routing_number") - @ExcludeMissing - private val routingNumber: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val accountName: JsonField, + private val accountNumber: JsonField, + private val accountType: JsonField, + private val institutionName: JsonField, + private val routingNumber: JsonField, + private val additionalProperties: MutableMap, ) { - /** The name of the bank associated in the payroll/HRIS system. */ - fun accountName(): Optional = - Optional.ofNullable(accountName.getNullable("account_name")) + @JsonCreator + private constructor( + @JsonProperty("account_name") + @ExcludeMissing + accountName: JsonField = JsonMissing.of(), + @JsonProperty("account_number") + @ExcludeMissing + accountNumber: JsonField = JsonMissing.of(), + @JsonProperty("account_type") + @ExcludeMissing + accountType: JsonField = JsonMissing.of(), + @JsonProperty("institution_name") + @ExcludeMissing + institutionName: JsonField = JsonMissing.of(), + @JsonProperty("routing_number") + @ExcludeMissing + routingNumber: JsonField = JsonMissing.of(), + ) : this( + accountName, + accountNumber, + accountType, + institutionName, + routingNumber, + mutableMapOf(), + ) - /** 10-12 digit number to specify the bank account */ - fun accountNumber(): Optional = - Optional.ofNullable(accountNumber.getNullable("account_number")) + /** + * The name of the bank associated in the payroll/HRIS system. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun accountName(): Optional = accountName.getOptional("account_name") - /** The type of bank account. */ - fun accountType(): Optional = - Optional.ofNullable(accountType.getNullable("account_type")) + /** + * 10-12 digit number to specify the bank account + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun accountNumber(): Optional = accountNumber.getOptional("account_number") - /** Name of the banking institution. */ - fun institutionName(): Optional = - Optional.ofNullable(institutionName.getNullable("institution_name")) + /** + * The type of bank account. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun accountType(): Optional = accountType.getOptional("account_type") + + /** + * Name of the banking institution. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun institutionName(): Optional = institutionName.getOptional("institution_name") /** * A nine-digit code that's based on the U.S. Bank location where your account was opened. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun routingNumber(): Optional = - Optional.ofNullable(routingNumber.getNullable("routing_number")) + fun routingNumber(): Optional = routingNumber.getOptional("routing_number") - /** The name of the bank associated in the payroll/HRIS system. */ + /** + * Returns the raw JSON value of [accountName]. + * + * Unlike [accountName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("account_name") @ExcludeMissing fun _accountName(): JsonField = accountName - /** 10-12 digit number to specify the bank account */ + /** + * Returns the raw JSON value of [accountNumber]. + * + * Unlike [accountNumber], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("account_number") @ExcludeMissing fun _accountNumber(): JsonField = accountNumber - /** The type of bank account. */ + /** + * Returns the raw JSON value of [accountType]. + * + * Unlike [accountType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("account_type") @ExcludeMissing fun _accountType(): JsonField = accountType - /** Name of the banking institution. */ + /** + * Returns the raw JSON value of [institutionName]. + * + * Unlike [institutionName], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("institution_name") @ExcludeMissing fun _institutionName(): JsonField = institutionName /** - * A nine-digit code that's based on the U.S. Bank location where your account was opened. + * Returns the raw JSON value of [routingNumber]. + * + * Unlike [routingNumber], this method doesn't throw if the JSON field has an unexpected + * type. */ @JsonProperty("routing_number") @ExcludeMissing fun _routingNumber(): JsonField = routingNumber + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Account = apply { - if (validated) { - return@apply - } - - accountName() - accountNumber() - accountType() - institutionName() - routingNumber() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Account]. */ @JvmStatic fun builder() = Builder() } @@ -439,10 +679,16 @@ private constructor( /** The name of the bank associated in the payroll/HRIS system. */ fun accountName(accountName: String?) = accountName(JsonField.ofNullable(accountName)) - /** The name of the bank associated in the payroll/HRIS system. */ - fun accountName(accountName: Optional) = accountName(accountName.orElse(null)) + /** Alias for calling [Builder.accountName] with `accountName.orElse(null)`. */ + fun accountName(accountName: Optional) = accountName(accountName.getOrNull()) - /** The name of the bank associated in the payroll/HRIS system. */ + /** + * Sets [Builder.accountName] to an arbitrary JSON value. + * + * You should usually call [Builder.accountName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun accountName(accountName: JsonField) = apply { this.accountName = accountName } @@ -451,11 +697,17 @@ private constructor( fun accountNumber(accountNumber: String?) = accountNumber(JsonField.ofNullable(accountNumber)) - /** 10-12 digit number to specify the bank account */ + /** Alias for calling [Builder.accountNumber] with `accountNumber.orElse(null)`. */ fun accountNumber(accountNumber: Optional) = - accountNumber(accountNumber.orElse(null)) + accountNumber(accountNumber.getOrNull()) - /** 10-12 digit number to specify the bank account */ + /** + * Sets [Builder.accountNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.accountNumber] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun accountNumber(accountNumber: JsonField) = apply { this.accountNumber = accountNumber } @@ -464,11 +716,17 @@ private constructor( fun accountType(accountType: AccountType?) = accountType(JsonField.ofNullable(accountType)) - /** The type of bank account. */ + /** Alias for calling [Builder.accountType] with `accountType.orElse(null)`. */ fun accountType(accountType: Optional) = - accountType(accountType.orElse(null)) + accountType(accountType.getOrNull()) - /** The type of bank account. */ + /** + * Sets [Builder.accountType] to an arbitrary JSON value. + * + * You should usually call [Builder.accountType] with a well-typed [AccountType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun accountType(accountType: JsonField) = apply { this.accountType = accountType } @@ -477,11 +735,17 @@ private constructor( fun institutionName(institutionName: String?) = institutionName(JsonField.ofNullable(institutionName)) - /** Name of the banking institution. */ + /** Alias for calling [Builder.institutionName] with `institutionName.orElse(null)`. */ fun institutionName(institutionName: Optional) = - institutionName(institutionName.orElse(null)) + institutionName(institutionName.getOrNull()) - /** Name of the banking institution. */ + /** + * Sets [Builder.institutionName] to an arbitrary JSON value. + * + * You should usually call [Builder.institutionName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun institutionName(institutionName: JsonField) = apply { this.institutionName = institutionName } @@ -493,16 +757,16 @@ private constructor( fun routingNumber(routingNumber: String?) = routingNumber(JsonField.ofNullable(routingNumber)) - /** - * A nine-digit code that's based on the U.S. Bank location where your account was - * opened. - */ + /** Alias for calling [Builder.routingNumber] with `routingNumber.orElse(null)`. */ fun routingNumber(routingNumber: Optional) = - routingNumber(routingNumber.orElse(null)) + routingNumber(routingNumber.getOrNull()) /** - * A nine-digit code that's based on the U.S. Bank location where your account was - * opened. + * Sets [Builder.routingNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.routingNumber] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun routingNumber(routingNumber: JsonField) = apply { this.routingNumber = routingNumber @@ -527,6 +791,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Account]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Account = Account( accountName, @@ -534,10 +803,47 @@ private constructor( accountType, institutionName, routingNumber, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Account = apply { + if (validated) { + return@apply + } + + accountName() + accountNumber() + accountType().ifPresent { it.validate() } + institutionName() + routingNumber() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountName.asKnown().isPresent) 1 else 0) + + (if (accountNumber.asKnown().isPresent) 1 else 0) + + (accountType.asKnown().getOrNull()?.validity() ?: 0) + + (if (institutionName.asKnown().isPresent) 1 else 0) + + (if (routingNumber.asKnown().isPresent) 1 else 0) + /** The type of bank account. */ class AccountType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -630,6 +936,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): AccountType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -661,52 +994,64 @@ private constructor( "Account{accountName=$accountName, accountNumber=$accountNumber, accountType=$accountType, institutionName=$institutionName, routingNumber=$routingNumber, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Department - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("parent") - @ExcludeMissing - private val parent: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val parent: JsonField, + private val additionalProperties: MutableMap, ) { - /** The department name. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("parent") @ExcludeMissing parent: JsonField = JsonMissing.of(), + ) : this(name, parent, mutableMapOf()) + + /** + * The department name. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** The parent department, if present. */ - fun parent(): Optional = Optional.ofNullable(parent.getNullable("parent")) + /** + * The parent department, if present. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun parent(): Optional = parent.getOptional("parent") - /** The department name. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** The parent department, if present. */ + /** + * Returns the raw JSON value of [parent]. + * + * Unlike [parent], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("parent") @ExcludeMissing fun _parent(): JsonField = parent + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Department = apply { - if (validated) { - return@apply - } - - name() - parent().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Department]. */ @JvmStatic fun builder() = Builder() } @@ -727,19 +1072,31 @@ private constructor( /** The department name. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The department name. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The department name. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } /** The parent department, if present. */ fun parent(parent: Parent?) = parent(JsonField.ofNullable(parent)) - /** The parent department, if present. */ - fun parent(parent: Optional) = parent(parent.orElse(null)) + /** Alias for calling [Builder.parent] with `parent.orElse(null)`. */ + fun parent(parent: Optional) = parent(parent.getOrNull()) - /** The parent department, if present. */ + /** + * Sets [Builder.parent] to an arbitrary JSON value. + * + * You should usually call [Builder.parent] with a well-typed [Parent] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun parent(parent: JsonField) = apply { this.parent = parent } fun additionalProperties(additionalProperties: Map) = apply { @@ -761,46 +1118,87 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Department = Department(name, parent, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Department]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Department = Department(name, parent, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Department = apply { + if (validated) { + return@apply + } + + name() + parent().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (parent.asKnown().getOrNull()?.validity() ?: 0) + /** The parent department, if present. */ - @NoAutoDetect class Parent - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - /** The parent department's name. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) - /** The parent department's name. */ + /** + * The parent department's name. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Parent = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Parent]. */ @JvmStatic fun builder() = Builder() } @@ -819,10 +1217,16 @@ private constructor( /** The parent department's name. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The parent department's name. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The parent department's name. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = apply { @@ -847,9 +1251,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Parent = Parent(name, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Parent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Parent = Parent(name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Parent = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -887,50 +1323,64 @@ private constructor( } /** The entity type object. */ - @NoAutoDetect class Entity - @JsonCreator private constructor( - @JsonProperty("subtype") - @ExcludeMissing - private val subtype: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val subtype: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The tax payer subtype of the company. */ - fun subtype(): Optional = Optional.ofNullable(subtype.getNullable("subtype")) + @JsonCreator + private constructor( + @JsonProperty("subtype") @ExcludeMissing subtype: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(subtype, type, mutableMapOf()) - /** The tax payer type of the company. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The tax payer subtype of the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun subtype(): Optional = subtype.getOptional("subtype") - /** The tax payer subtype of the company. */ + /** + * The tax payer type of the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [subtype]. + * + * Unlike [subtype], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype - /** The tax payer type of the company. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Entity = apply { - if (validated) { - return@apply - } - - subtype() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Entity]. */ @JvmStatic fun builder() = Builder() } @@ -951,19 +1401,31 @@ private constructor( /** The tax payer subtype of the company. */ fun subtype(subtype: Subtype?) = subtype(JsonField.ofNullable(subtype)) - /** The tax payer subtype of the company. */ - fun subtype(subtype: Optional) = subtype(subtype.orElse(null)) + /** Alias for calling [Builder.subtype] with `subtype.orElse(null)`. */ + fun subtype(subtype: Optional) = subtype(subtype.getOrNull()) - /** The tax payer subtype of the company. */ + /** + * Sets [Builder.subtype] to an arbitrary JSON value. + * + * You should usually call [Builder.subtype] with a well-typed [Subtype] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun subtype(subtype: JsonField) = apply { this.subtype = subtype } /** The tax payer type of the company. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** The tax payer type of the company. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** The tax payer type of the company. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -985,9 +1447,45 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Entity = Entity(subtype, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Entity]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Entity = Entity(subtype, type, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Entity = apply { + if (validated) { + return@apply + } + + subtype().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (subtype.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + /** The tax payer subtype of the company. */ class Subtype @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1085,6 +1583,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Subtype = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1216,6 +1741,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectSessionNewParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectSessionNewParams.kt index 622a3456..eb6903d6 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectSessionNewParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectSessionNewParams.kt @@ -11,16 +11,17 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Create a new connect session for an employer */ class ConnectSessionNewParams @@ -30,42 +31,123 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun customerId(): String = body.customerId() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun customerName(): String = body.customerName() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun products(): List = body.products() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun customerEmail(): Optional = body.customerEmail() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun integration(): Optional = body.integration() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun manual(): Optional = body.manual() - /** The number of minutes until the session expires (defaults to 43,200, which is 30 days) */ + /** + * The number of minutes until the session expires (defaults to 43,200, which is 30 days) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun minutesToExpire(): Optional = body.minutesToExpire() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun redirectUri(): Optional = body.redirectUri() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun sandbox(): Optional = body.sandbox() + /** + * Returns the raw JSON value of [customerId]. + * + * Unlike [customerId], this method doesn't throw if the JSON field has an unexpected type. + */ fun _customerId(): JsonField = body._customerId() + /** + * Returns the raw JSON value of [customerName]. + * + * Unlike [customerName], this method doesn't throw if the JSON field has an unexpected type. + */ fun _customerName(): JsonField = body._customerName() + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ fun _products(): JsonField> = body._products() + /** + * Returns the raw JSON value of [customerEmail]. + * + * Unlike [customerEmail], this method doesn't throw if the JSON field has an unexpected type. + */ fun _customerEmail(): JsonField = body._customerEmail() + /** + * Returns the raw JSON value of [integration]. + * + * Unlike [integration], this method doesn't throw if the JSON field has an unexpected type. + */ fun _integration(): JsonField = body._integration() + /** + * Returns the raw JSON value of [manual]. + * + * Unlike [manual], this method doesn't throw if the JSON field has an unexpected type. + */ fun _manual(): JsonField = body._manual() - /** The number of minutes until the session expires (defaults to 43,200, which is 30 days) */ + /** + * Returns the raw JSON value of [minutesToExpire]. + * + * Unlike [minutesToExpire], this method doesn't throw if the JSON field has an unexpected type. + */ fun _minutesToExpire(): JsonField = body._minutesToExpire() + /** + * Returns the raw JSON value of [redirectUri]. + * + * Unlike [redirectUri], this method doesn't throw if the JSON field has an unexpected type. + */ fun _redirectUri(): JsonField = body._redirectUri() + /** + * Returns the raw JSON value of [sandbox]. + * + * Unlike [sandbox], this method doesn't throw if the JSON field has an unexpected type. + */ fun _sandbox(): JsonField = body._sandbox() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -74,134 +156,559 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ConnectSessionNewParams]. + * + * The following fields are required: + * ```java + * .customerId() + * .customerName() + * .products() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ConnectSessionNewParams]. */ + class Builder internal constructor() { + + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(connectSessionNewParams: ConnectSessionNewParams) = apply { + body = connectSessionNewParams.body.toBuilder() + additionalHeaders = connectSessionNewParams.additionalHeaders.toBuilder() + additionalQueryParams = connectSessionNewParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [customerId] + * - [customerName] + * - [products] + * - [customerEmail] + * - [integration] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + fun customerId(customerId: String) = apply { body.customerId(customerId) } + + /** + * Sets [Builder.customerId] to an arbitrary JSON value. + * + * You should usually call [Builder.customerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun customerId(customerId: JsonField) = apply { body.customerId(customerId) } + + fun customerName(customerName: String) = apply { body.customerName(customerName) } + + /** + * Sets [Builder.customerName] to an arbitrary JSON value. + * + * You should usually call [Builder.customerName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun customerName(customerName: JsonField) = apply { + body.customerName(customerName) + } + + fun products(products: List) = apply { body.products(products) } + + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun products(products: JsonField>) = apply { body.products(products) } + + /** + * Adds a single [ConnectProducts] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addProduct(product: ConnectProducts) = apply { body.addProduct(product) } + + fun customerEmail(customerEmail: String?) = apply { body.customerEmail(customerEmail) } + + /** Alias for calling [Builder.customerEmail] with `customerEmail.orElse(null)`. */ + fun customerEmail(customerEmail: Optional) = + customerEmail(customerEmail.getOrNull()) + + /** + * Sets [Builder.customerEmail] to an arbitrary JSON value. + * + * You should usually call [Builder.customerEmail] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun customerEmail(customerEmail: JsonField) = apply { + body.customerEmail(customerEmail) + } + + fun integration(integration: Integration?) = apply { body.integration(integration) } + + /** Alias for calling [Builder.integration] with `integration.orElse(null)`. */ + fun integration(integration: Optional) = integration(integration.getOrNull()) + + /** + * Sets [Builder.integration] to an arbitrary JSON value. + * + * You should usually call [Builder.integration] with a well-typed [Integration] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun integration(integration: JsonField) = apply { + body.integration(integration) + } + + fun manual(manual: Boolean?) = apply { body.manual(manual) } + + /** + * Alias for [Builder.manual]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun manual(manual: Boolean) = manual(manual as Boolean?) + + /** Alias for calling [Builder.manual] with `manual.orElse(null)`. */ + fun manual(manual: Optional) = manual(manual.getOrNull()) + + /** + * Sets [Builder.manual] to an arbitrary JSON value. + * + * You should usually call [Builder.manual] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun manual(manual: JsonField) = apply { body.manual(manual) } + + /** + * The number of minutes until the session expires (defaults to 43,200, which is 30 days) + */ + fun minutesToExpire(minutesToExpire: Double?) = apply { + body.minutesToExpire(minutesToExpire) + } + + /** + * Alias for [Builder.minutesToExpire]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun minutesToExpire(minutesToExpire: Double) = minutesToExpire(minutesToExpire as Double?) + + /** Alias for calling [Builder.minutesToExpire] with `minutesToExpire.orElse(null)`. */ + fun minutesToExpire(minutesToExpire: Optional) = + minutesToExpire(minutesToExpire.getOrNull()) + + /** + * Sets [Builder.minutesToExpire] to an arbitrary JSON value. + * + * You should usually call [Builder.minutesToExpire] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun minutesToExpire(minutesToExpire: JsonField) = apply { + body.minutesToExpire(minutesToExpire) + } + + fun redirectUri(redirectUri: String?) = apply { body.redirectUri(redirectUri) } + + /** Alias for calling [Builder.redirectUri] with `redirectUri.orElse(null)`. */ + fun redirectUri(redirectUri: Optional) = redirectUri(redirectUri.getOrNull()) + + /** + * Sets [Builder.redirectUri] to an arbitrary JSON value. + * + * You should usually call [Builder.redirectUri] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun redirectUri(redirectUri: JsonField) = apply { body.redirectUri(redirectUri) } + + fun sandbox(sandbox: Sandbox?) = apply { body.sandbox(sandbox) } + + /** Alias for calling [Builder.sandbox] with `sandbox.orElse(null)`. */ + fun sandbox(sandbox: Optional) = sandbox(sandbox.getOrNull()) + + /** + * Sets [Builder.sandbox] to an arbitrary JSON value. + * + * You should usually call [Builder.sandbox] with a well-typed [Sandbox] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun sandbox(sandbox: JsonField) = apply { body.sandbox(sandbox) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [ConnectSessionNewParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .customerId() + * .customerName() + * .products() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ConnectSessionNewParams = + ConnectSessionNewParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams - @NoAutoDetect class Body - @JsonCreator private constructor( - @JsonProperty("customer_id") - @ExcludeMissing - private val customerId: JsonField = JsonMissing.of(), - @JsonProperty("customer_name") - @ExcludeMissing - private val customerName: JsonField = JsonMissing.of(), - @JsonProperty("products") - @ExcludeMissing - private val products: JsonField> = JsonMissing.of(), - @JsonProperty("customer_email") - @ExcludeMissing - private val customerEmail: JsonField = JsonMissing.of(), - @JsonProperty("integration") - @ExcludeMissing - private val integration: JsonField = JsonMissing.of(), - @JsonProperty("manual") - @ExcludeMissing - private val manual: JsonField = JsonMissing.of(), - @JsonProperty("minutes_to_expire") - @ExcludeMissing - private val minutesToExpire: JsonField = JsonMissing.of(), - @JsonProperty("redirect_uri") - @ExcludeMissing - private val redirectUri: JsonField = JsonMissing.of(), - @JsonProperty("sandbox") - @ExcludeMissing - private val sandbox: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val customerId: JsonField, + private val customerName: JsonField, + private val products: JsonField>, + private val customerEmail: JsonField, + private val integration: JsonField, + private val manual: JsonField, + private val minutesToExpire: JsonField, + private val redirectUri: JsonField, + private val sandbox: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("customer_id") + @ExcludeMissing + customerId: JsonField = JsonMissing.of(), + @JsonProperty("customer_name") + @ExcludeMissing + customerName: JsonField = JsonMissing.of(), + @JsonProperty("products") + @ExcludeMissing + products: JsonField> = JsonMissing.of(), + @JsonProperty("customer_email") + @ExcludeMissing + customerEmail: JsonField = JsonMissing.of(), + @JsonProperty("integration") + @ExcludeMissing + integration: JsonField = JsonMissing.of(), + @JsonProperty("manual") @ExcludeMissing manual: JsonField = JsonMissing.of(), + @JsonProperty("minutes_to_expire") + @ExcludeMissing + minutesToExpire: JsonField = JsonMissing.of(), + @JsonProperty("redirect_uri") + @ExcludeMissing + redirectUri: JsonField = JsonMissing.of(), + @JsonProperty("sandbox") @ExcludeMissing sandbox: JsonField = JsonMissing.of(), + ) : this( + customerId, + customerName, + products, + customerEmail, + integration, + manual, + minutesToExpire, + redirectUri, + sandbox, + mutableMapOf(), + ) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ fun customerId(): String = customerId.getRequired("customer_id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ fun customerName(): String = customerName.getRequired("customer_name") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ fun products(): List = products.getRequired("products") - fun customerEmail(): Optional = - Optional.ofNullable(customerEmail.getNullable("customer_email")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customerEmail(): Optional = customerEmail.getOptional("customer_email") - fun integration(): Optional = - Optional.ofNullable(integration.getNullable("integration")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun integration(): Optional = integration.getOptional("integration") - fun manual(): Optional = Optional.ofNullable(manual.getNullable("manual")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun manual(): Optional = manual.getOptional("manual") /** * The number of minutes until the session expires (defaults to 43,200, which is 30 days) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun minutesToExpire(): Optional = - Optional.ofNullable(minutesToExpire.getNullable("minutes_to_expire")) + fun minutesToExpire(): Optional = minutesToExpire.getOptional("minutes_to_expire") - fun redirectUri(): Optional = - Optional.ofNullable(redirectUri.getNullable("redirect_uri")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun redirectUri(): Optional = redirectUri.getOptional("redirect_uri") - fun sandbox(): Optional = Optional.ofNullable(sandbox.getNullable("sandbox")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun sandbox(): Optional = sandbox.getOptional("sandbox") + /** + * Returns the raw JSON value of [customerId]. + * + * Unlike [customerId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("customer_id") @ExcludeMissing fun _customerId(): JsonField = customerId + /** + * Returns the raw JSON value of [customerName]. + * + * Unlike [customerName], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("customer_name") @ExcludeMissing fun _customerName(): JsonField = customerName + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("products") @ExcludeMissing fun _products(): JsonField> = products + /** + * Returns the raw JSON value of [customerEmail]. + * + * Unlike [customerEmail], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("customer_email") @ExcludeMissing fun _customerEmail(): JsonField = customerEmail + /** + * Returns the raw JSON value of [integration]. + * + * Unlike [integration], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("integration") @ExcludeMissing fun _integration(): JsonField = integration + /** + * Returns the raw JSON value of [manual]. + * + * Unlike [manual], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("manual") @ExcludeMissing fun _manual(): JsonField = manual /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 days) + * Returns the raw JSON value of [minutesToExpire]. + * + * Unlike [minutesToExpire], this method doesn't throw if the JSON field has an unexpected + * type. */ @JsonProperty("minutes_to_expire") @ExcludeMissing fun _minutesToExpire(): JsonField = minutesToExpire + /** + * Returns the raw JSON value of [redirectUri]. + * + * Unlike [redirectUri], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("redirect_uri") @ExcludeMissing fun _redirectUri(): JsonField = redirectUri + /** + * Returns the raw JSON value of [sandbox]. + * + * Unlike [sandbox], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("sandbox") @ExcludeMissing fun _sandbox(): JsonField = sandbox + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - customerId() - customerName() - products() - customerEmail() - integration().ifPresent { it.validate() } - manual() - minutesToExpire() - redirectUri() - sandbox() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .customerId() + * .customerName() + * .products() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -235,39 +742,67 @@ private constructor( fun customerId(customerId: String) = customerId(JsonField.of(customerId)) + /** + * Sets [Builder.customerId] to an arbitrary JSON value. + * + * You should usually call [Builder.customerId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun customerId(customerId: JsonField) = apply { this.customerId = customerId } fun customerName(customerName: String) = customerName(JsonField.of(customerName)) + /** + * Sets [Builder.customerName] to an arbitrary JSON value. + * + * You should usually call [Builder.customerName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun customerName(customerName: JsonField) = apply { this.customerName = customerName } fun products(products: List) = products(JsonField.of(products)) + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun products(products: JsonField>) = apply { this.products = products.map { it.toMutableList() } } + /** + * Adds a single [ConnectProducts] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addProduct(product: ConnectProducts) = apply { products = - (products ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(product) + (products ?: JsonField.of(mutableListOf())).also { + checkKnown("products", it).add(product) } } fun customerEmail(customerEmail: String?) = customerEmail(JsonField.ofNullable(customerEmail)) + /** Alias for calling [Builder.customerEmail] with `customerEmail.orElse(null)`. */ fun customerEmail(customerEmail: Optional) = - customerEmail(customerEmail.orElse(null)) + customerEmail(customerEmail.getOrNull()) + /** + * Sets [Builder.customerEmail] to an arbitrary JSON value. + * + * You should usually call [Builder.customerEmail] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun customerEmail(customerEmail: JsonField) = apply { this.customerEmail = customerEmail } @@ -275,343 +810,211 @@ private constructor( fun integration(integration: Integration?) = integration(JsonField.ofNullable(integration)) + /** Alias for calling [Builder.integration] with `integration.orElse(null)`. */ fun integration(integration: Optional) = - integration(integration.orElse(null)) + integration(integration.getOrNull()) + /** + * Sets [Builder.integration] to an arbitrary JSON value. + * + * You should usually call [Builder.integration] with a well-typed [Integration] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun integration(integration: JsonField) = apply { this.integration = integration } fun manual(manual: Boolean?) = manual(JsonField.ofNullable(manual)) - fun manual(manual: Boolean) = manual(manual as Boolean?) - - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun manual(manual: Optional) = manual(manual.orElse(null) as Boolean?) - - fun manual(manual: JsonField) = apply { this.manual = manual } - /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 - * days) + * Alias for [Builder.manual]. + * + * This unboxed primitive overload exists for backwards compatibility. */ - fun minutesToExpire(minutesToExpire: Double?) = - minutesToExpire(JsonField.ofNullable(minutesToExpire)) + fun manual(manual: Boolean) = manual(manual as Boolean?) - /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 - * days) - */ - fun minutesToExpire(minutesToExpire: Double) = - minutesToExpire(minutesToExpire as Double?) + /** Alias for calling [Builder.manual] with `manual.orElse(null)`. */ + fun manual(manual: Optional) = manual(manual.getOrNull()) /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 - * days) + * Sets [Builder.manual] to an arbitrary JSON value. + * + * You should usually call [Builder.manual] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun minutesToExpire(minutesToExpire: Optional) = - minutesToExpire(minutesToExpire.orElse(null) as Double?) + fun manual(manual: JsonField) = apply { this.manual = manual } /** * The number of minutes until the session expires (defaults to 43,200, which is 30 * days) - */ - fun minutesToExpire(minutesToExpire: JsonField) = apply { - this.minutesToExpire = minutesToExpire - } - - fun redirectUri(redirectUri: String?) = redirectUri(JsonField.ofNullable(redirectUri)) - - fun redirectUri(redirectUri: Optional) = redirectUri(redirectUri.orElse(null)) - - fun redirectUri(redirectUri: JsonField) = apply { - this.redirectUri = redirectUri - } - - fun sandbox(sandbox: Sandbox?) = sandbox(JsonField.ofNullable(sandbox)) - - fun sandbox(sandbox: Optional) = sandbox(sandbox.orElse(null)) - - fun sandbox(sandbox: JsonField) = apply { this.sandbox = sandbox } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = - Body( - checkRequired("customerId", customerId), - checkRequired("customerName", customerName), - checkRequired("products", products).map { it.toImmutable() }, - customerEmail, - integration, - manual, - minutesToExpire, - redirectUri, - sandbox, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && customerId == other.customerId && customerName == other.customerName && products == other.products && customerEmail == other.customerEmail && integration == other.integration && manual == other.manual && minutesToExpire == other.minutesToExpire && redirectUri == other.redirectUri && sandbox == other.sandbox && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(customerId, customerName, products, customerEmail, integration, manual, minutesToExpire, redirectUri, sandbox, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{customerId=$customerId, customerName=$customerName, products=$products, customerEmail=$customerEmail, integration=$integration, manual=$manual, minutesToExpire=$minutesToExpire, redirectUri=$redirectUri, sandbox=$sandbox, additionalProperties=$additionalProperties}" - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [ConnectSessionNewParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var body: Body.Builder = Body.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - - @JvmSynthetic - internal fun from(connectSessionNewParams: ConnectSessionNewParams) = apply { - body = connectSessionNewParams.body.toBuilder() - additionalHeaders = connectSessionNewParams.additionalHeaders.toBuilder() - additionalQueryParams = connectSessionNewParams.additionalQueryParams.toBuilder() - } - - fun customerId(customerId: String) = apply { body.customerId(customerId) } - - fun customerId(customerId: JsonField) = apply { body.customerId(customerId) } - - fun customerName(customerName: String) = apply { body.customerName(customerName) } - - fun customerName(customerName: JsonField) = apply { - body.customerName(customerName) - } - - fun products(products: List) = apply { body.products(products) } - - fun products(products: JsonField>) = apply { body.products(products) } - - fun addProduct(product: ConnectProducts) = apply { body.addProduct(product) } - - fun customerEmail(customerEmail: String?) = apply { body.customerEmail(customerEmail) } - - fun customerEmail(customerEmail: Optional) = - customerEmail(customerEmail.orElse(null)) - - fun customerEmail(customerEmail: JsonField) = apply { - body.customerEmail(customerEmail) - } - - fun integration(integration: Integration?) = apply { body.integration(integration) } - - fun integration(integration: Optional) = integration(integration.orElse(null)) - - fun integration(integration: JsonField) = apply { - body.integration(integration) - } - - fun manual(manual: Boolean?) = apply { body.manual(manual) } - - fun manual(manual: Boolean) = manual(manual as Boolean?) - - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun manual(manual: Optional) = manual(manual.orElse(null) as Boolean?) - - fun manual(manual: JsonField) = apply { body.manual(manual) } - - /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 days) - */ - fun minutesToExpire(minutesToExpire: Double?) = apply { - body.minutesToExpire(minutesToExpire) - } - - /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 days) - */ - fun minutesToExpire(minutesToExpire: Double) = minutesToExpire(minutesToExpire as Double?) - - /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 days) - */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun minutesToExpire(minutesToExpire: Optional) = - minutesToExpire(minutesToExpire.orElse(null) as Double?) - - /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 days) - */ - fun minutesToExpire(minutesToExpire: JsonField) = apply { - body.minutesToExpire(minutesToExpire) - } - - fun redirectUri(redirectUri: String?) = apply { body.redirectUri(redirectUri) } - - fun redirectUri(redirectUri: Optional) = redirectUri(redirectUri.orElse(null)) - - fun redirectUri(redirectUri: JsonField) = apply { body.redirectUri(redirectUri) } - - fun sandbox(sandbox: Sandbox?) = apply { body.sandbox(sandbox) } - - fun sandbox(sandbox: Optional) = sandbox(sandbox.orElse(null)) - - fun sandbox(sandbox: JsonField) = apply { body.sandbox(sandbox) } - - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } - - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } - - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } - - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } - - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + */ + fun minutesToExpire(minutesToExpire: Double?) = + minutesToExpire(JsonField.ofNullable(minutesToExpire)) - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Alias for [Builder.minutesToExpire]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun minutesToExpire(minutesToExpire: Double) = + minutesToExpire(minutesToExpire as Double?) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** Alias for calling [Builder.minutesToExpire] with `minutesToExpire.orElse(null)`. */ + fun minutesToExpire(minutesToExpire: Optional) = + minutesToExpire(minutesToExpire.getOrNull()) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Sets [Builder.minutesToExpire] to an arbitrary JSON value. + * + * You should usually call [Builder.minutesToExpire] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun minutesToExpire(minutesToExpire: JsonField) = apply { + this.minutesToExpire = minutesToExpire + } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + fun redirectUri(redirectUri: String?) = redirectUri(JsonField.ofNullable(redirectUri)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.redirectUri] with `redirectUri.orElse(null)`. */ + fun redirectUri(redirectUri: Optional) = redirectUri(redirectUri.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.redirectUri] to an arbitrary JSON value. + * + * You should usually call [Builder.redirectUri] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun redirectUri(redirectUri: JsonField) = apply { + this.redirectUri = redirectUri + } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + fun sandbox(sandbox: Sandbox?) = sandbox(JsonField.ofNullable(sandbox)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.sandbox] with `sandbox.orElse(null)`. */ + fun sandbox(sandbox: Optional) = sandbox(sandbox.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.sandbox] to an arbitrary JSON value. + * + * You should usually call [Builder.sandbox] with a well-typed [Sandbox] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sandbox(sandbox: JsonField) = apply { this.sandbox = sandbox } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .customerId() + * .customerName() + * .products() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("customerId", customerId), + checkRequired("customerName", customerName), + checkRequired("products", products).map { it.toImmutable() }, + customerEmail, + integration, + manual, + minutesToExpire, + redirectUri, + sandbox, + additionalProperties.toMutableMap(), + ) } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + private var validated: Boolean = false - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun validate(): Body = apply { + if (validated) { + return@apply } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + customerId() + customerName() + products().forEach { it.validate() } + customerEmail() + integration().ifPresent { it.validate() } + manual() + minutesToExpire() + redirectUri() + sandbox().ifPresent { it.validate() } + validated = true } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (customerId.asKnown().isPresent) 1 else 0) + + (if (customerName.asKnown().isPresent) 1 else 0) + + (products.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (customerEmail.asKnown().isPresent) 1 else 0) + + (integration.asKnown().getOrNull()?.validity() ?: 0) + + (if (manual.asKnown().isPresent) 1 else 0) + + (if (minutesToExpire.asKnown().isPresent) 1 else 0) + + (if (redirectUri.asKnown().isPresent) 1 else 0) + + (sandbox.asKnown().getOrNull()?.validity() ?: 0) - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + return /* spotless:off */ other is Body && customerId == other.customerId && customerName == other.customerName && products == other.products && customerEmail == other.customerEmail && integration == other.integration && manual == other.manual && minutesToExpire == other.minutesToExpire && redirectUri == other.redirectUri && sandbox == other.sandbox && additionalProperties == other.additionalProperties /* spotless:on */ } - fun build(): ConnectSessionNewParams = - ConnectSessionNewParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(customerId, customerName, products, customerEmail, integration, manual, minutesToExpire, redirectUri, sandbox, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{customerId=$customerId, customerName=$customerName, products=$products, customerEmail=$customerEmail, integration=$integration, manual=$manual, minutesToExpire=$minutesToExpire, redirectUri=$redirectUri, sandbox=$sandbox, additionalProperties=$additionalProperties}" } /** The Finch products that can be requested during the Connect flow. */ @@ -739,6 +1142,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ConnectProducts = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -752,51 +1182,64 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class Integration - @JsonCreator private constructor( - @JsonProperty("auth_method") - @ExcludeMissing - private val authMethod: JsonField = JsonMissing.of(), - @JsonProperty("provider") - @ExcludeMissing - private val provider: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val authMethod: JsonField, + private val provider: JsonField, + private val additionalProperties: MutableMap, ) { - fun authMethod(): Optional = - Optional.ofNullable(authMethod.getNullable("auth_method")) + @JsonCreator + private constructor( + @JsonProperty("auth_method") + @ExcludeMissing + authMethod: JsonField = JsonMissing.of(), + @JsonProperty("provider") @ExcludeMissing provider: JsonField = JsonMissing.of(), + ) : this(authMethod, provider, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun authMethod(): Optional = authMethod.getOptional("auth_method") - fun provider(): Optional = Optional.ofNullable(provider.getNullable("provider")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun provider(): Optional = provider.getOptional("provider") + /** + * Returns the raw JSON value of [authMethod]. + * + * Unlike [authMethod], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("auth_method") @ExcludeMissing fun _authMethod(): JsonField = authMethod + /** + * Returns the raw JSON value of [provider]. + * + * Unlike [provider], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("provider") @ExcludeMissing fun _provider(): JsonField = provider + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Integration = apply { - if (validated) { - return@apply - } - - authMethod() - provider() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Integration]. */ @JvmStatic fun builder() = Builder() } @@ -816,16 +1259,32 @@ private constructor( fun authMethod(authMethod: AuthMethod?) = authMethod(JsonField.ofNullable(authMethod)) - fun authMethod(authMethod: Optional) = authMethod(authMethod.orElse(null)) + /** Alias for calling [Builder.authMethod] with `authMethod.orElse(null)`. */ + fun authMethod(authMethod: Optional) = authMethod(authMethod.getOrNull()) + /** + * Sets [Builder.authMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.authMethod] with a well-typed [AuthMethod] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun authMethod(authMethod: JsonField) = apply { this.authMethod = authMethod } fun provider(provider: String?) = provider(JsonField.ofNullable(provider)) - fun provider(provider: Optional) = provider(provider.orElse(null)) + /** Alias for calling [Builder.provider] with `provider.orElse(null)`. */ + fun provider(provider: Optional) = provider(provider.getOrNull()) + /** + * Sets [Builder.provider] to an arbitrary JSON value. + * + * You should usually call [Builder.provider] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun provider(provider: JsonField) = apply { this.provider = provider } fun additionalProperties(additionalProperties: Map) = apply { @@ -847,10 +1306,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Integration]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Integration = - Integration(authMethod, provider, additionalProperties.toImmutable()) + Integration(authMethod, provider, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Integration = apply { + if (validated) { + return@apply + } + + authMethod().ifPresent { it.validate() } + provider() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (authMethod.asKnown().getOrNull()?.validity() ?: 0) + + (if (provider.asKnown().isPresent) 1 else 0) + class AuthMethod @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -954,6 +1449,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): AuthMethod = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1069,6 +1591,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Sandbox = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectSessionReauthenticateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectSessionReauthenticateParams.kt index 50101242..5968625d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectSessionReauthenticateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectSessionReauthenticateParams.kt @@ -11,16 +11,17 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Create a new Connect session for reauthenticating an existing connection */ class ConnectSessionReauthenticateParams @@ -30,28 +31,64 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { - /** The ID of the existing connection to reauthenticate */ + /** + * The ID of the existing connection to reauthenticate + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun connectionId(): String = body.connectionId() - /** The number of minutes until the session expires (defaults to 43,200, which is 30 days) */ + /** + * The number of minutes until the session expires (defaults to 43,200, which is 30 days) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun minutesToExpire(): Optional = body.minutesToExpire() - /** The products to request access to (optional for reauthentication) */ + /** + * The products to request access to (optional for reauthentication) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun products(): Optional> = body.products() - /** The URI to redirect to after the Connect flow is completed */ + /** + * The URI to redirect to after the Connect flow is completed + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun redirectUri(): Optional = body.redirectUri() - /** The ID of the existing connection to reauthenticate */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ fun _connectionId(): JsonField = body._connectionId() - /** The number of minutes until the session expires (defaults to 43,200, which is 30 days) */ + /** + * Returns the raw JSON value of [minutesToExpire]. + * + * Unlike [minutesToExpire], this method doesn't throw if the JSON field has an unexpected type. + */ fun _minutesToExpire(): JsonField = body._minutesToExpire() - /** The products to request access to (optional for reauthentication) */ + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ fun _products(): JsonField> = body._products() - /** The URI to redirect to after the Connect flow is completed */ + /** + * Returns the raw JSON value of [redirectUri]. + * + * Unlike [redirectUri], this method doesn't throw if the JSON field has an unexpected type. + */ fun _redirectUri(): JsonField = body._redirectUri() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -60,245 +97,23 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("minutes_to_expire") - @ExcludeMissing - private val minutesToExpire: JsonField = JsonMissing.of(), - @JsonProperty("products") - @ExcludeMissing - private val products: JsonField> = JsonMissing.of(), - @JsonProperty("redirect_uri") - @ExcludeMissing - private val redirectUri: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** The ID of the existing connection to reauthenticate */ - fun connectionId(): String = connectionId.getRequired("connection_id") - - /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 days) - */ - fun minutesToExpire(): Optional = - Optional.ofNullable(minutesToExpire.getNullable("minutes_to_expire")) - - /** The products to request access to (optional for reauthentication) */ - fun products(): Optional> = - Optional.ofNullable(products.getNullable("products")) - - /** The URI to redirect to after the Connect flow is completed */ - fun redirectUri(): Optional = - Optional.ofNullable(redirectUri.getNullable("redirect_uri")) - - /** The ID of the existing connection to reauthenticate */ - @JsonProperty("connection_id") - @ExcludeMissing - fun _connectionId(): JsonField = connectionId - - /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 days) - */ - @JsonProperty("minutes_to_expire") - @ExcludeMissing - fun _minutesToExpire(): JsonField = minutesToExpire - - /** The products to request access to (optional for reauthentication) */ - @JsonProperty("products") - @ExcludeMissing - fun _products(): JsonField> = products - - /** The URI to redirect to after the Connect flow is completed */ - @JsonProperty("redirect_uri") - @ExcludeMissing - fun _redirectUri(): JsonField = redirectUri - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - connectionId() - minutesToExpire() - products() - redirectUri() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var connectionId: JsonField? = null - private var minutesToExpire: JsonField = JsonMissing.of() - private var products: JsonField>? = null - private var redirectUri: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - connectionId = body.connectionId - minutesToExpire = body.minutesToExpire - products = body.products.map { it.toMutableList() } - redirectUri = body.redirectUri - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** The ID of the existing connection to reauthenticate */ - fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - - /** The ID of the existing connection to reauthenticate */ - fun connectionId(connectionId: JsonField) = apply { - this.connectionId = connectionId - } - - /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 - * days) - */ - fun minutesToExpire(minutesToExpire: Long?) = - minutesToExpire(JsonField.ofNullable(minutesToExpire)) - - /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 - * days) - */ - fun minutesToExpire(minutesToExpire: Long) = minutesToExpire(minutesToExpire as Long?) - - /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 - * days) - */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun minutesToExpire(minutesToExpire: Optional) = - minutesToExpire(minutesToExpire.orElse(null) as Long?) - - /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 - * days) - */ - fun minutesToExpire(minutesToExpire: JsonField) = apply { - this.minutesToExpire = minutesToExpire - } - - /** The products to request access to (optional for reauthentication) */ - fun products(products: List?) = - products(JsonField.ofNullable(products)) - - /** The products to request access to (optional for reauthentication) */ - fun products(products: Optional>) = - products(products.orElse(null)) - - /** The products to request access to (optional for reauthentication) */ - fun products(products: JsonField>) = apply { - this.products = products.map { it.toMutableList() } - } - - /** The products to request access to (optional for reauthentication) */ - fun addProduct(product: ConnectProducts) = apply { - products = - (products ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(product) - } - } - - /** The URI to redirect to after the Connect flow is completed */ - fun redirectUri(redirectUri: String?) = redirectUri(JsonField.ofNullable(redirectUri)) - - /** The URI to redirect to after the Connect flow is completed */ - fun redirectUri(redirectUri: Optional) = redirectUri(redirectUri.orElse(null)) - - /** The URI to redirect to after the Connect flow is completed */ - fun redirectUri(redirectUri: JsonField) = apply { - this.redirectUri = redirectUri - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = - Body( - checkRequired("connectionId", connectionId), - minutesToExpire, - (products ?: JsonMissing.of()).map { it.toImmutable() }, - redirectUri, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && connectionId == other.connectionId && minutesToExpire == other.minutesToExpire && products == other.products && redirectUri == other.redirectUri && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(connectionId, minutesToExpire, products, redirectUri, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{connectionId=$connectionId, minutesToExpire=$minutesToExpire, products=$products, redirectUri=$redirectUri, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [ConnectSessionReauthenticateParams]. + * + * The following fields are required: + * ```java + * .connectionId() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [ConnectSessionReauthenticateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -314,10 +129,28 @@ private constructor( connectSessionReauthenticateParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [connectionId] + * - [minutesToExpire] + * - [products] + * - [redirectUri] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** The ID of the existing connection to reauthenticate */ fun connectionId(connectionId: String) = apply { body.connectionId(connectionId) } - /** The ID of the existing connection to reauthenticate */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { body.connectionId(connectionId) } @@ -330,19 +163,22 @@ private constructor( } /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 days) + * Alias for [Builder.minutesToExpire]. + * + * This unboxed primitive overload exists for backwards compatibility. */ fun minutesToExpire(minutesToExpire: Long) = minutesToExpire(minutesToExpire as Long?) - /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 days) - */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 + /** Alias for calling [Builder.minutesToExpire] with `minutesToExpire.orElse(null)`. */ fun minutesToExpire(minutesToExpire: Optional) = - minutesToExpire(minutesToExpire.orElse(null) as Long?) + minutesToExpire(minutesToExpire.getOrNull()) /** - * The number of minutes until the session expires (defaults to 43,200, which is 30 days) + * Sets [Builder.minutesToExpire] to an arbitrary JSON value. + * + * You should usually call [Builder.minutesToExpire] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ fun minutesToExpire(minutesToExpire: JsonField) = apply { body.minutesToExpire(minutesToExpire) @@ -351,22 +187,38 @@ private constructor( /** The products to request access to (optional for reauthentication) */ fun products(products: List?) = apply { body.products(products) } - /** The products to request access to (optional for reauthentication) */ - fun products(products: Optional>) = products(products.orElse(null)) + /** Alias for calling [Builder.products] with `products.orElse(null)`. */ + fun products(products: Optional>) = products(products.getOrNull()) - /** The products to request access to (optional for reauthentication) */ + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun products(products: JsonField>) = apply { body.products(products) } - /** The products to request access to (optional for reauthentication) */ + /** + * Adds a single [ConnectProducts] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addProduct(product: ConnectProducts) = apply { body.addProduct(product) } /** The URI to redirect to after the Connect flow is completed */ fun redirectUri(redirectUri: String?) = apply { body.redirectUri(redirectUri) } - /** The URI to redirect to after the Connect flow is completed */ - fun redirectUri(redirectUri: Optional) = redirectUri(redirectUri.orElse(null)) + /** Alias for calling [Builder.redirectUri] with `redirectUri.orElse(null)`. */ + fun redirectUri(redirectUri: Optional) = redirectUri(redirectUri.getOrNull()) - /** The URI to redirect to after the Connect flow is completed */ + /** + * Sets [Builder.redirectUri] to an arbitrary JSON value. + * + * You should usually call [Builder.redirectUri] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun redirectUri(redirectUri: JsonField) = apply { body.redirectUri(redirectUri) } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { @@ -486,6 +338,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [ConnectSessionReauthenticateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .connectionId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): ConnectSessionReauthenticateParams = ConnectSessionReauthenticateParams( body.build(), @@ -494,6 +358,334 @@ private constructor( ) } + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val connectionId: JsonField, + private val minutesToExpire: JsonField, + private val products: JsonField>, + private val redirectUri: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("minutes_to_expire") + @ExcludeMissing + minutesToExpire: JsonField = JsonMissing.of(), + @JsonProperty("products") + @ExcludeMissing + products: JsonField> = JsonMissing.of(), + @JsonProperty("redirect_uri") + @ExcludeMissing + redirectUri: JsonField = JsonMissing.of(), + ) : this(connectionId, minutesToExpire, products, redirectUri, mutableMapOf()) + + /** + * The ID of the existing connection to reauthenticate + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun connectionId(): String = connectionId.getRequired("connection_id") + + /** + * The number of minutes until the session expires (defaults to 43,200, which is 30 days) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun minutesToExpire(): Optional = minutesToExpire.getOptional("minutes_to_expire") + + /** + * The products to request access to (optional for reauthentication) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun products(): Optional> = products.getOptional("products") + + /** + * The URI to redirect to after the Connect flow is completed + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun redirectUri(): Optional = redirectUri.getOptional("redirect_uri") + + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("connection_id") + @ExcludeMissing + fun _connectionId(): JsonField = connectionId + + /** + * Returns the raw JSON value of [minutesToExpire]. + * + * Unlike [minutesToExpire], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("minutes_to_expire") + @ExcludeMissing + fun _minutesToExpire(): JsonField = minutesToExpire + + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("products") + @ExcludeMissing + fun _products(): JsonField> = products + + /** + * Returns the raw JSON value of [redirectUri]. + * + * Unlike [redirectUri], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("redirect_uri") + @ExcludeMissing + fun _redirectUri(): JsonField = redirectUri + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .connectionId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var connectionId: JsonField? = null + private var minutesToExpire: JsonField = JsonMissing.of() + private var products: JsonField>? = null + private var redirectUri: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + connectionId = body.connectionId + minutesToExpire = body.minutesToExpire + products = body.products.map { it.toMutableList() } + redirectUri = body.redirectUri + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The ID of the existing connection to reauthenticate */ + fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) + + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun connectionId(connectionId: JsonField) = apply { + this.connectionId = connectionId + } + + /** + * The number of minutes until the session expires (defaults to 43,200, which is 30 + * days) + */ + fun minutesToExpire(minutesToExpire: Long?) = + minutesToExpire(JsonField.ofNullable(minutesToExpire)) + + /** + * Alias for [Builder.minutesToExpire]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun minutesToExpire(minutesToExpire: Long) = minutesToExpire(minutesToExpire as Long?) + + /** Alias for calling [Builder.minutesToExpire] with `minutesToExpire.orElse(null)`. */ + fun minutesToExpire(minutesToExpire: Optional) = + minutesToExpire(minutesToExpire.getOrNull()) + + /** + * Sets [Builder.minutesToExpire] to an arbitrary JSON value. + * + * You should usually call [Builder.minutesToExpire] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun minutesToExpire(minutesToExpire: JsonField) = apply { + this.minutesToExpire = minutesToExpire + } + + /** The products to request access to (optional for reauthentication) */ + fun products(products: List?) = + products(JsonField.ofNullable(products)) + + /** Alias for calling [Builder.products] with `products.orElse(null)`. */ + fun products(products: Optional>) = products(products.getOrNull()) + + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun products(products: JsonField>) = apply { + this.products = products.map { it.toMutableList() } + } + + /** + * Adds a single [ConnectProducts] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addProduct(product: ConnectProducts) = apply { + products = + (products ?: JsonField.of(mutableListOf())).also { + checkKnown("products", it).add(product) + } + } + + /** The URI to redirect to after the Connect flow is completed */ + fun redirectUri(redirectUri: String?) = redirectUri(JsonField.ofNullable(redirectUri)) + + /** Alias for calling [Builder.redirectUri] with `redirectUri.orElse(null)`. */ + fun redirectUri(redirectUri: Optional) = redirectUri(redirectUri.getOrNull()) + + /** + * Sets [Builder.redirectUri] to an arbitrary JSON value. + * + * You should usually call [Builder.redirectUri] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun redirectUri(redirectUri: JsonField) = apply { + this.redirectUri = redirectUri + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .connectionId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("connectionId", connectionId), + minutesToExpire, + (products ?: JsonMissing.of()).map { it.toImmutable() }, + redirectUri, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + connectionId() + minutesToExpire() + products().ifPresent { it.forEach { it.validate() } } + redirectUri() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (connectionId.asKnown().isPresent) 1 else 0) + + (if (minutesToExpire.asKnown().isPresent) 1 else 0) + + (products.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (redirectUri.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && connectionId == other.connectionId && minutesToExpire == other.minutesToExpire && products == other.products && redirectUri == other.redirectUri && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(connectionId, minutesToExpire, products, redirectUri, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{connectionId=$connectionId, minutesToExpire=$minutesToExpire, products=$products, redirectUri=$redirectUri, additionalProperties=$additionalProperties}" + } + /** The Finch products that can be requested during the Connect flow. */ class ConnectProducts @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -619,6 +811,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ConnectProducts = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectionCreateResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectionCreateResponse.kt index 36084ea1..0bc05880 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectionCreateResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectionCreateResponse.kt @@ -11,124 +11,214 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class ConnectionCreateResponse -@JsonCreator private constructor( - @JsonProperty("access_token") - @ExcludeMissing - private val accessToken: JsonField = JsonMissing.of(), - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("authentication_type") - @ExcludeMissing - private val authenticationType: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("products") - @ExcludeMissing - private val products: JsonField> = JsonMissing.of(), - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonProperty("token_type") - @ExcludeMissing - private val tokenType: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accessToken: JsonField, + private val accountId: JsonField, + private val authenticationType: JsonField, + private val companyId: JsonField, + private val connectionId: JsonField, + private val products: JsonField>, + private val providerId: JsonField, + private val tokenType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("access_token") + @ExcludeMissing + accessToken: JsonField = JsonMissing.of(), + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("authentication_type") + @ExcludeMissing + authenticationType: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("products") + @ExcludeMissing + products: JsonField> = JsonMissing.of(), + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + @JsonProperty("token_type") @ExcludeMissing tokenType: JsonField = JsonMissing.of(), + ) : this( + accessToken, + accountId, + authenticationType, + companyId, + connectionId, + products, + providerId, + tokenType, + mutableMapOf(), + ) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun accessToken(): String = accessToken.getRequired("access_token") - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * [DEPRECATED] Use `connection_id` to associate a connection with an access token + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun authenticationType(): AuthenticationType = authenticationType.getRequired("authentication_type") - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * [DEPRECATED] Use `connection_id` to associate a connection with an access token + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") - /** The ID of the new connection */ + /** + * The ID of the new connection + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun connectionId(): String = connectionId.getRequired("connection_id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun products(): List = products.getRequired("products") - /** The ID of the provider associated with the `access_token`. */ + /** + * The ID of the provider associated with the `access_token`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun providerId(): String = providerId.getRequired("provider_id") - fun tokenType(): Optional = Optional.ofNullable(tokenType.getNullable("token_type")) - + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tokenType(): Optional = tokenType.getOptional("token_type") + + /** + * Returns the raw JSON value of [accessToken]. + * + * Unlike [accessToken], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("access_token") @ExcludeMissing fun _accessToken(): JsonField = accessToken - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. + */ @Deprecated("deprecated") @JsonProperty("account_id") @ExcludeMissing fun _accountId(): JsonField = accountId + /** + * Returns the raw JSON value of [authenticationType]. + * + * Unlike [authenticationType], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("authentication_type") @ExcludeMissing fun _authenticationType(): JsonField = authenticationType - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. + */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - /** The ID of the new connection */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("products") @ExcludeMissing fun _products(): JsonField> = products - /** The ID of the provider associated with the `access_token`. */ + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("provider_id") @ExcludeMissing fun _providerId(): JsonField = providerId + /** + * Returns the raw JSON value of [tokenType]. + * + * Unlike [tokenType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("token_type") @ExcludeMissing fun _tokenType(): JsonField = tokenType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ConnectionCreateResponse = apply { - if (validated) { - return@apply - } - - accessToken() - accountId() - authenticationType() - companyId() - connectionId() - products() - providerId() - tokenType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [ConnectionCreateResponse]. + * + * The following fields are required: + * ```java + * .accessToken() + * .accountId() + * .authenticationType() + * .companyId() + * .connectionId() + * .products() + * .providerId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -160,19 +250,39 @@ private constructor( fun accessToken(accessToken: String) = accessToken(JsonField.of(accessToken)) + /** + * Sets [Builder.accessToken] to an arbitrary JSON value. + * + * You should usually call [Builder.accessToken] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun accessToken(accessToken: JsonField) = apply { this.accessToken = accessToken } /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ @Deprecated("deprecated") fun accountId(accountId: String) = accountId(JsonField.of(accountId)) - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } fun authenticationType(authenticationType: AuthenticationType) = authenticationType(JsonField.of(authenticationType)) + /** + * Sets [Builder.authenticationType] to an arbitrary JSON value. + * + * You should usually call [Builder.authenticationType] with a well-typed + * [AuthenticationType] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun authenticationType(authenticationType: JsonField) = apply { this.authenticationType = authenticationType } @@ -181,45 +291,76 @@ private constructor( @Deprecated("deprecated") fun companyId(companyId: String) = companyId(JsonField.of(companyId)) - /** [DEPRECATED] Use `connection_id` to associate a connection with an access token */ + /** + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } /** The ID of the new connection */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** The ID of the new connection */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } fun products(products: List) = products(JsonField.of(products)) + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun products(products: JsonField>) = apply { this.products = products.map { it.toMutableList() } } + /** + * Adds a single [String] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addProduct(product: String) = apply { products = - (products ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(product) + (products ?: JsonField.of(mutableListOf())).also { + checkKnown("products", it).add(product) } } /** The ID of the provider associated with the `access_token`. */ fun providerId(providerId: String) = providerId(JsonField.of(providerId)) - /** The ID of the provider associated with the `access_token`. */ + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun providerId(providerId: JsonField) = apply { this.providerId = providerId } fun tokenType(tokenType: String) = tokenType(JsonField.of(tokenType)) + /** + * Sets [Builder.tokenType] to an arbitrary JSON value. + * + * You should usually call [Builder.tokenType] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun tokenType(tokenType: JsonField) = apply { this.tokenType = tokenType } fun additionalProperties(additionalProperties: Map) = apply { @@ -241,6 +382,24 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [ConnectionCreateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accessToken() + * .accountId() + * .authenticationType() + * .companyId() + * .connectionId() + * .products() + * .providerId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): ConnectionCreateResponse = ConnectionCreateResponse( checkRequired("accessToken", accessToken), @@ -251,10 +410,52 @@ private constructor( checkRequired("products", products).map { it.toImmutable() }, checkRequired("providerId", providerId), tokenType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ConnectionCreateResponse = apply { + if (validated) { + return@apply + } + + accessToken() + accountId() + authenticationType().validate() + companyId() + connectionId() + products() + providerId() + tokenType() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accessToken.asKnown().isPresent) 1 else 0) + + (if (accountId.asKnown().isPresent) 1 else 0) + + (authenticationType.asKnown().getOrNull()?.validity() ?: 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + + (products.asKnown().getOrNull()?.size ?: 0) + + (if (providerId.asKnown().isPresent) 1 else 0) + + (if (tokenType.asKnown().isPresent) 1 else 0) + class AuthenticationType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -356,6 +557,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): AuthenticationType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectionStatusType.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectionStatusType.kt index 8911a636..08471c42 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectionStatusType.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ConnectionStatusType.kt @@ -118,6 +118,32 @@ class ConnectionStatusType @JsonCreator private constructor(private val value: J fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ConnectionStatusType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CreateAccessTokenResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CreateAccessTokenResponse.kt index 1030bc51..02a73edf 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CreateAccessTokenResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CreateAccessTokenResponse.kt @@ -11,167 +11,266 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class CreateAccessTokenResponse -@JsonCreator private constructor( - @JsonProperty("access_token") - @ExcludeMissing - private val accessToken: JsonField = JsonMissing.of(), - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("client_type") - @ExcludeMissing - private val clientType: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("connection_type") - @ExcludeMissing - private val connectionType: JsonField = JsonMissing.of(), - @JsonProperty("products") - @ExcludeMissing - private val products: JsonField> = JsonMissing.of(), - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonProperty("customer_id") - @ExcludeMissing - private val customerId: JsonField = JsonMissing.of(), - @JsonProperty("token_type") - @ExcludeMissing - private val tokenType: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accessToken: JsonField, + private val accountId: JsonField, + private val clientType: JsonField, + private val companyId: JsonField, + private val connectionId: JsonField, + private val connectionType: JsonField, + private val products: JsonField>, + private val providerId: JsonField, + private val customerId: JsonField, + private val tokenType: JsonField, + private val additionalProperties: MutableMap, ) { - /** The access token for the connection. */ + @JsonCreator + private constructor( + @JsonProperty("access_token") + @ExcludeMissing + accessToken: JsonField = JsonMissing.of(), + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("client_type") + @ExcludeMissing + clientType: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("connection_type") + @ExcludeMissing + connectionType: JsonField = JsonMissing.of(), + @JsonProperty("products") + @ExcludeMissing + products: JsonField> = JsonMissing.of(), + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + @JsonProperty("customer_id") + @ExcludeMissing + customerId: JsonField = JsonMissing.of(), + @JsonProperty("token_type") @ExcludeMissing tokenType: JsonField = JsonMissing.of(), + ) : this( + accessToken, + accountId, + clientType, + companyId, + connectionId, + connectionType, + products, + providerId, + customerId, + tokenType, + mutableMapOf(), + ) + + /** + * The access token for the connection. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun accessToken(): String = accessToken.getRequired("access_token") - /** [DEPRECATED] Use `connection_id` to identify the connection instead of this account ID. */ + /** + * [DEPRECATED] Use `connection_id` to identify the connection instead of this account ID. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") - /** The type of application associated with a token. */ + /** + * The type of application associated with a token. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun clientType(): ClientType = clientType.getRequired("client_type") - /** [DEPRECATED] Use `connection_id` to identify the connection instead of this company ID. */ + /** + * [DEPRECATED] Use `connection_id` to identify the connection instead of this company ID. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") - /** The Finch UUID of the connection associated with the `access_token`. */ + /** + * The Finch UUID of the connection associated with the `access_token`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun connectionId(): String = connectionId.getRequired("connection_id") /** * The type of the connection associated with the token. * - `provider` - connection to an external provider * - `finch` - finch-generated data. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ fun connectionType(): ConnectionType = connectionType.getRequired("connection_type") - /** An array of the authorized products associated with the `access_token`. */ + /** + * An array of the authorized products associated with the `access_token`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun products(): List = products.getRequired("products") - /** The ID of the provider associated with the `access_token`. */ + /** + * The ID of the provider associated with the `access_token`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun providerId(): String = providerId.getRequired("provider_id") /** * The ID of your customer you provided to Finch when a connect session was created for this * connection. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun customerId(): Optional = Optional.ofNullable(customerId.getNullable("customer_id")) + fun customerId(): Optional = customerId.getOptional("customer_id") - /** The RFC 8693 token type (Finch uses `bearer` tokens) */ - fun tokenType(): Optional = Optional.ofNullable(tokenType.getNullable("token_type")) + /** + * The RFC 8693 token type (Finch uses `bearer` tokens) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun tokenType(): Optional = tokenType.getOptional("token_type") - /** The access token for the connection. */ + /** + * Returns the raw JSON value of [accessToken]. + * + * Unlike [accessToken], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("access_token") @ExcludeMissing fun _accessToken(): JsonField = accessToken - /** [DEPRECATED] Use `connection_id` to identify the connection instead of this account ID. */ + /** + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. + */ @Deprecated("deprecated") @JsonProperty("account_id") @ExcludeMissing fun _accountId(): JsonField = accountId - /** The type of application associated with a token. */ + /** + * Returns the raw JSON value of [clientType]. + * + * Unlike [clientType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("client_type") @ExcludeMissing fun _clientType(): JsonField = clientType - /** [DEPRECATED] Use `connection_id` to identify the connection instead of this company ID. */ + /** + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. + */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - /** The Finch UUID of the connection associated with the `access_token`. */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId /** - * The type of the connection associated with the token. - * - `provider` - connection to an external provider - * - `finch` - finch-generated data. + * Returns the raw JSON value of [connectionType]. + * + * Unlike [connectionType], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("connection_type") @ExcludeMissing fun _connectionType(): JsonField = connectionType - /** An array of the authorized products associated with the `access_token`. */ + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("products") @ExcludeMissing fun _products(): JsonField> = products - /** The ID of the provider associated with the `access_token`. */ + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("provider_id") @ExcludeMissing fun _providerId(): JsonField = providerId /** - * The ID of your customer you provided to Finch when a connect session was created for this - * connection. + * Returns the raw JSON value of [customerId]. + * + * Unlike [customerId], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("customer_id") @ExcludeMissing fun _customerId(): JsonField = customerId - /** The RFC 8693 token type (Finch uses `bearer` tokens) */ + /** + * Returns the raw JSON value of [tokenType]. + * + * Unlike [tokenType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("token_type") @ExcludeMissing fun _tokenType(): JsonField = tokenType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): CreateAccessTokenResponse = apply { - if (validated) { - return@apply - } - - accessToken() - accountId() - clientType() - companyId() - connectionId() - connectionType() - products() - providerId() - customerId() - tokenType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [CreateAccessTokenResponse]. + * + * The following fields are required: + * ```java + * .accessToken() + * .accountId() + * .clientType() + * .companyId() + * .connectionId() + * .connectionType() + * .products() + * .providerId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -208,7 +307,13 @@ private constructor( /** The access token for the connection. */ fun accessToken(accessToken: String) = accessToken(JsonField.of(accessToken)) - /** The access token for the connection. */ + /** + * Sets [Builder.accessToken] to an arbitrary JSON value. + * + * You should usually call [Builder.accessToken] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun accessToken(accessToken: JsonField) = apply { this.accessToken = accessToken } /** @@ -218,7 +323,11 @@ private constructor( fun accountId(accountId: String) = accountId(JsonField.of(accountId)) /** - * [DEPRECATED] Use `connection_id` to identify the connection instead of this account ID. + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } @@ -226,7 +335,13 @@ private constructor( /** The type of application associated with a token. */ fun clientType(clientType: ClientType) = clientType(JsonField.of(clientType)) - /** The type of application associated with a token. */ + /** + * Sets [Builder.clientType] to an arbitrary JSON value. + * + * You should usually call [Builder.clientType] with a well-typed [ClientType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun clientType(clientType: JsonField) = apply { this.clientType = clientType } /** @@ -236,7 +351,11 @@ private constructor( fun companyId(companyId: String) = companyId(JsonField.of(companyId)) /** - * [DEPRECATED] Use `connection_id` to identify the connection instead of this company ID. + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } @@ -244,7 +363,13 @@ private constructor( /** The Finch UUID of the connection associated with the `access_token`. */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** The Finch UUID of the connection associated with the `access_token`. */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } @@ -258,9 +383,11 @@ private constructor( connectionType(JsonField.of(connectionType)) /** - * The type of the connection associated with the token. - * - `provider` - connection to an external provider - * - `finch` - finch-generated data. + * Sets [Builder.connectionType] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionType] with a well-typed [ConnectionType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun connectionType(connectionType: JsonField) = apply { this.connectionType = connectionType @@ -269,29 +396,39 @@ private constructor( /** An array of the authorized products associated with the `access_token`. */ fun products(products: List) = products(JsonField.of(products)) - /** An array of the authorized products associated with the `access_token`. */ + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun products(products: JsonField>) = apply { this.products = products.map { it.toMutableList() } } - /** An array of the authorized products associated with the `access_token`. */ + /** + * Adds a single [String] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addProduct(product: String) = apply { products = - (products ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(product) + (products ?: JsonField.of(mutableListOf())).also { + checkKnown("products", it).add(product) } } /** The ID of the provider associated with the `access_token`. */ fun providerId(providerId: String) = providerId(JsonField.of(providerId)) - /** The ID of the provider associated with the `access_token`. */ + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun providerId(providerId: JsonField) = apply { this.providerId = providerId } /** @@ -300,22 +437,28 @@ private constructor( */ fun customerId(customerId: String?) = customerId(JsonField.ofNullable(customerId)) - /** - * The ID of your customer you provided to Finch when a connect session was created for this - * connection. - */ - fun customerId(customerId: Optional) = customerId(customerId.orElse(null)) + /** Alias for calling [Builder.customerId] with `customerId.orElse(null)`. */ + fun customerId(customerId: Optional) = customerId(customerId.getOrNull()) /** - * The ID of your customer you provided to Finch when a connect session was created for this - * connection. + * Sets [Builder.customerId] to an arbitrary JSON value. + * + * You should usually call [Builder.customerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ fun customerId(customerId: JsonField) = apply { this.customerId = customerId } /** The RFC 8693 token type (Finch uses `bearer` tokens) */ fun tokenType(tokenType: String) = tokenType(JsonField.of(tokenType)) - /** The RFC 8693 token type (Finch uses `bearer` tokens) */ + /** + * Sets [Builder.tokenType] to an arbitrary JSON value. + * + * You should usually call [Builder.tokenType] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun tokenType(tokenType: JsonField) = apply { this.tokenType = tokenType } fun additionalProperties(additionalProperties: Map) = apply { @@ -337,6 +480,25 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [CreateAccessTokenResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accessToken() + * .accountId() + * .clientType() + * .companyId() + * .connectionId() + * .connectionType() + * .products() + * .providerId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): CreateAccessTokenResponse = CreateAccessTokenResponse( checkRequired("accessToken", accessToken), @@ -349,10 +511,56 @@ private constructor( checkRequired("providerId", providerId), customerId, tokenType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): CreateAccessTokenResponse = apply { + if (validated) { + return@apply + } + + accessToken() + accountId() + clientType().validate() + companyId() + connectionId() + connectionType().validate() + products() + providerId() + customerId() + tokenType() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accessToken.asKnown().isPresent) 1 else 0) + + (if (accountId.asKnown().isPresent) 1 else 0) + + (clientType.asKnown().getOrNull()?.validity() ?: 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + + (connectionType.asKnown().getOrNull()?.validity() ?: 0) + + (products.asKnown().getOrNull()?.size ?: 0) + + (if (providerId.asKnown().isPresent) 1 else 0) + + (if (customerId.asKnown().isPresent) 1 else 0) + + (if (tokenType.asKnown().isPresent) 1 else 0) + /** The type of application associated with a token. */ class ClientType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -446,6 +654,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ClientType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -552,6 +787,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ConnectionType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CreateCompanyBenefitsResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CreateCompanyBenefitsResponse.kt index c526676e..16e0501e 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CreateCompanyBenefitsResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/CreateCompanyBenefitsResponse.kt @@ -10,45 +10,60 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects -@NoAutoDetect class CreateCompanyBenefitsResponse -@JsonCreator private constructor( - @JsonProperty("benefit_id") - @ExcludeMissing - private val benefitId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val benefitId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("benefit_id") @ExcludeMissing benefitId: JsonField = JsonMissing.of() + ) : this(benefitId, mutableMapOf()) + + /** + * The id of the benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun benefitId(): String = benefitId.getRequired("benefit_id") + /** + * Returns the raw JSON value of [benefitId]. + * + * Unlike [benefitId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("benefit_id") @ExcludeMissing fun _benefitId(): JsonField = benefitId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): CreateCompanyBenefitsResponse = apply { - if (validated) { - return@apply - } - - benefitId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [CreateCompanyBenefitsResponse]. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -64,8 +79,16 @@ private constructor( additionalProperties = createCompanyBenefitsResponse.additionalProperties.toMutableMap() } + /** The id of the benefit. */ fun benefitId(benefitId: String) = benefitId(JsonField.of(benefitId)) + /** + * Sets [Builder.benefitId] to an arbitrary JSON value. + * + * You should usually call [Builder.benefitId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun benefitId(benefitId: JsonField) = apply { this.benefitId = benefitId } fun additionalProperties(additionalProperties: Map) = apply { @@ -87,13 +110,51 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [CreateCompanyBenefitsResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): CreateCompanyBenefitsResponse = CreateCompanyBenefitsResponse( checkRequired("benefitId", benefitId), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): CreateCompanyBenefitsResponse = apply { + if (validated) { + return@apply + } + + benefitId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (benefitId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DirectoryCreateResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DirectoryCreateResponse.kt new file mode 100644 index 00000000..0efe9871 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DirectoryCreateResponse.kt @@ -0,0 +1,115 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.tryfinch.api.core.ExcludeMissing +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections +import java.util.Objects + +class DirectoryCreateResponse +private constructor(private val additionalProperties: MutableMap) { + + @JsonCreator private constructor() : this(mutableMapOf()) + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [DirectoryCreateResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [DirectoryCreateResponse]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(directoryCreateResponse: DirectoryCreateResponse) = apply { + additionalProperties = directoryCreateResponse.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [DirectoryCreateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): DirectoryCreateResponse = + DirectoryCreateResponse(additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): DirectoryCreateResponse = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = 0 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is DirectoryCreateResponse && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = "DirectoryCreateResponse{additionalProperties=$additionalProperties}" +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DirectoryEvent.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DirectoryEvent.kt index 078fdd80..96280779 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DirectoryEvent.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DirectoryEvent.kt @@ -11,57 +11,85 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class DirectoryEvent -@JsonCreator private constructor( - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("data") @ExcludeMissing private val data: JsonField = JsonMissing.of(), - @JsonProperty("event_type") - @ExcludeMissing - private val eventType: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accountId: JsonField, + private val companyId: JsonField, + private val connectionId: JsonField, + private val data: JsonField, + private val eventType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("event_type") + @ExcludeMissing + eventType: JsonField = JsonMissing.of(), + ) : this(accountId, companyId, connectionId, data, eventType, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder() + .accountId(accountId) + .companyId(companyId) + .connectionId(connectionId) + .build() + /** * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") /** * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") - /** Unique Finch ID of the connection associated with the webhook event. */ - fun connectionId(): Optional = - Optional.ofNullable(connectionId.getNullable("connection_id")) + /** + * Unique Finch ID of the connection associated with the webhook event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun connectionId(): Optional = connectionId.getOptional("connection_id") - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") - fun eventType(): Optional = Optional.ofNullable(eventType.getNullable("event_type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun eventType(): Optional = eventType.getOptional("event_type") /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("account_id") @@ -69,53 +97,61 @@ private constructor( fun _accountId(): JsonField = accountId /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [eventType]. + * + * Unlike [eventType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("event_type") @ExcludeMissing fun _eventType(): JsonField = eventType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBaseWebhookEvent(): BaseWebhookEvent = - BaseWebhookEvent.builder() - .accountId(accountId) - .companyId(companyId) - .connectionId(connectionId) - .build() - - private var validated: Boolean = false - - fun validate(): DirectoryEvent = apply { - if (validated) { - return@apply - } - - accountId() - companyId() - connectionId() - data().ifPresent { it.validate() } - eventType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [DirectoryEvent]. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -147,8 +183,11 @@ private constructor( fun accountId(accountId: String) = accountId(JsonField.of(accountId)) /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } @@ -161,8 +200,11 @@ private constructor( fun companyId(companyId: String) = companyId(JsonField.of(companyId)) /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } @@ -170,17 +212,36 @@ private constructor( /** Unique Finch ID of the connection associated with the webhook event. */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } fun data(data: Data) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun eventType(eventType: EventType) = eventType(JsonField.of(eventType)) + /** + * Sets [Builder.eventType] to an arbitrary JSON value. + * + * You should usually call [Builder.eventType] with a well-typed [EventType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun eventType(eventType: JsonField) = apply { this.eventType = eventType } fun additionalProperties(additionalProperties: Map) = apply { @@ -202,6 +263,19 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [DirectoryEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): DirectoryEvent = DirectoryEvent( checkRequired("accountId", accountId), @@ -209,49 +283,92 @@ private constructor( connectionId, data, eventType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): DirectoryEvent = apply { + if (validated) { + return@apply + } + + accountId() + companyId() + connectionId() + data().ifPresent { it.validate() } + eventType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountId.asKnown().isPresent) 1 else 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (eventType.asKnown().getOrNull()?.validity() ?: 0) + class Data - @JsonCreator private constructor( - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val individualId: JsonField, + private val additionalProperties: MutableMap, ) { - /** The ID of the individual related to the event. */ - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) + @JsonCreator + private constructor( + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of() + ) : this(individualId, mutableMapOf()) + + /** + * The ID of the individual related to the event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") - /** The ID of the individual related to the event. */ + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Data = apply { - if (validated) { - return@apply - } - - individualId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Data]. */ @JvmStatic fun builder() = Builder() } @@ -270,7 +387,13 @@ private constructor( /** The ID of the individual related to the event. */ fun individualId(individualId: String) = individualId(JsonField.of(individualId)) - /** The ID of the individual related to the event. */ + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -294,9 +417,42 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Data = Data(individualId, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Data = Data(individualId, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + individualId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (individualId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -407,6 +563,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EventType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DisconnectResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DisconnectResponse.kt index a2b8ff0a..c46c0b60 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DisconnectResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DisconnectResponse.kt @@ -10,47 +10,59 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects -@NoAutoDetect class DisconnectResponse -@JsonCreator private constructor( - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val status: JsonField, + private val additionalProperties: MutableMap, ) { - /** If the request is successful, Finch will return “success” (HTTP 200 status). */ + @JsonCreator + private constructor( + @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of() + ) : this(status, mutableMapOf()) + + /** + * If the request is successful, Finch will return “success” (HTTP 200 status). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun status(): String = status.getRequired("status") - /** If the request is successful, Finch will return “success” (HTTP 200 status). */ + /** + * Returns the raw JSON value of [status]. + * + * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): DisconnectResponse = apply { - if (validated) { - return@apply - } - - status() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [DisconnectResponse]. + * + * The following fields are required: + * ```java + * .status() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -69,7 +81,12 @@ private constructor( /** If the request is successful, Finch will return “success” (HTTP 200 status). */ fun status(status: String) = status(JsonField.of(status)) - /** If the request is successful, Finch will return “success” (HTTP 200 status). */ + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun status(status: JsonField) = apply { this.status = status } fun additionalProperties(additionalProperties: Map) = apply { @@ -91,10 +108,48 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [DisconnectResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .status() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): DisconnectResponse = - DisconnectResponse(checkRequired("status", status), additionalProperties.toImmutable()) + DisconnectResponse(checkRequired("status", status), additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): DisconnectResponse = apply { + if (validated) { + return@apply + } + + status() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (status.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DocumentListResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DocumentListResponse.kt index ed73b872..85ef0727 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DocumentListResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DocumentListResponse.kt @@ -10,55 +10,80 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class DocumentListResponse -@JsonCreator private constructor( - @JsonProperty("documents") - @ExcludeMissing - private val documents: JsonField> = JsonMissing.of(), - @JsonProperty("paging") - @ExcludeMissing - private val paging: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val documents: JsonField>, + private val paging: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("documents") + @ExcludeMissing + documents: JsonField> = JsonMissing.of(), + @JsonProperty("paging") @ExcludeMissing paging: JsonField = JsonMissing.of(), + ) : this(documents, paging, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun documents(): List = documents.getRequired("documents") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun paging(): Paging = paging.getRequired("paging") + /** + * Returns the raw JSON value of [documents]. + * + * Unlike [documents], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("documents") @ExcludeMissing fun _documents(): JsonField> = documents + /** + * Returns the raw JSON value of [paging]. + * + * Unlike [paging], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("paging") @ExcludeMissing fun _paging(): JsonField = paging + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): DocumentListResponse = apply { - if (validated) { - return@apply - } - - documents().forEach { it.validate() } - paging().validate() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [DocumentListResponse]. + * + * The following fields are required: + * ```java + * .documents() + * .paging() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -78,25 +103,37 @@ private constructor( fun documents(documents: List) = documents(JsonField.of(documents)) + /** + * Sets [Builder.documents] to an arbitrary JSON value. + * + * You should usually call [Builder.documents] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun documents(documents: JsonField>) = apply { this.documents = documents.map { it.toMutableList() } } + /** + * Adds a single [DocumentResponse] to [documents]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addDocument(document: DocumentResponse) = apply { documents = - (documents ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(document) + (documents ?: JsonField.of(mutableListOf())).also { + checkKnown("documents", it).add(document) } } fun paging(paging: Paging) = paging(JsonField.of(paging)) + /** + * Sets [Builder.paging] to an arbitrary JSON value. + * + * You should usually call [Builder.paging] with a well-typed [Paging] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun paging(paging: JsonField) = apply { this.paging = paging } fun additionalProperties(additionalProperties: Map) = apply { @@ -118,14 +155,57 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [DocumentListResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .documents() + * .paging() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): DocumentListResponse = DocumentListResponse( checkRequired("documents", documents).map { it.toImmutable() }, checkRequired("paging", paging), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): DocumentListResponse = apply { + if (validated) { + return@apply + } + + documents().forEach { it.validate() } + paging().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (documents.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (paging.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DocumentResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DocumentResponse.kt index d0469b43..6dcd6bcb 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DocumentResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DocumentResponse.kt @@ -11,95 +11,127 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class DocumentResponse -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonProperty("url") @ExcludeMissing private val url: JsonField = JsonMissing.of(), - @JsonProperty("year") @ExcludeMissing private val year: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val individualId: JsonField, + private val type: JsonField, + private val url: JsonField, + private val year: JsonField, + private val additionalProperties: MutableMap, ) { - /** A stable Finch id for the document. */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("year") @ExcludeMissing year: JsonField = JsonMissing.of(), + ) : this(id, individualId, type, url, year, mutableMapOf()) + + /** + * A stable Finch id for the document. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") /** * The ID of the individual associated with the document. This will be null for employer-level * documents. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) + fun individualId(): Optional = individualId.getOptional("individual_id") - /** The type of document. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The type of document. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") /** * A URL to access the document. Format: * `https://api.tryfinch.com/employer/documents/:document_id`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun url(): Optional = Optional.ofNullable(url.getNullable("url")) + fun url(): Optional = url.getOptional("url") - /** The year the document applies to, if available. */ - fun year(): Optional = Optional.ofNullable(year.getNullable("year")) + /** + * The year the document applies to, if available. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun year(): Optional = year.getOptional("year") - /** A stable Finch id for the document. */ + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id /** - * The ID of the individual associated with the document. This will be null for employer-level - * documents. + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId - /** The type of document. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type /** - * A URL to access the document. Format: - * `https://api.tryfinch.com/employer/documents/:document_id`. + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url - /** The year the document applies to, if available. */ + /** + * Returns the raw JSON value of [year]. + * + * Unlike [year], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("year") @ExcludeMissing fun _year(): JsonField = year + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): DocumentResponse = apply { - if (validated) { - return@apply - } - - id() - individualId() - type() - url() - year() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [DocumentResponse]. */ @JvmStatic fun builder() = Builder() } @@ -126,7 +158,12 @@ private constructor( /** A stable Finch id for the document. */ fun id(id: String) = id(JsonField.of(id)) - /** A stable Finch id for the document. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } /** @@ -135,15 +172,15 @@ private constructor( */ fun individualId(individualId: String?) = individualId(JsonField.ofNullable(individualId)) - /** - * The ID of the individual associated with the document. This will be null for - * employer-level documents. - */ - fun individualId(individualId: Optional) = individualId(individualId.orElse(null)) + /** Alias for calling [Builder.individualId] with `individualId.orElse(null)`. */ + fun individualId(individualId: Optional) = individualId(individualId.getOrNull()) /** - * The ID of the individual associated with the document. This will be null for - * employer-level documents. + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId @@ -152,7 +189,12 @@ private constructor( /** The type of document. */ fun type(type: Type) = type(JsonField.of(type)) - /** The type of document. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } /** @@ -162,22 +204,32 @@ private constructor( fun url(url: String) = url(JsonField.of(url)) /** - * A URL to access the document. Format: - * `https://api.tryfinch.com/employer/documents/:document_id`. + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun url(url: JsonField) = apply { this.url = url } /** The year the document applies to, if available. */ fun year(year: Double?) = year(JsonField.ofNullable(year)) - /** The year the document applies to, if available. */ + /** + * Alias for [Builder.year]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun year(year: Double) = year(year as Double?) - /** The year the document applies to, if available. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun year(year: Optional) = year(year.orElse(null) as Double?) + /** Alias for calling [Builder.year] with `year.orElse(null)`. */ + fun year(year: Optional) = year(year.getOrNull()) - /** The year the document applies to, if available. */ + /** + * Sets [Builder.year] to an arbitrary JSON value. + * + * You should usually call [Builder.year] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun year(year: JsonField) = apply { this.year = year } fun additionalProperties(additionalProperties: Map) = apply { @@ -199,10 +251,51 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [DocumentResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): DocumentResponse = - DocumentResponse(id, individualId, type, url, year, additionalProperties.toImmutable()) + DocumentResponse(id, individualId, type, url, year, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): DocumentResponse = apply { + if (validated) { + return@apply + } + + id() + individualId() + type().ifPresent { it.validate() } + url() + year() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (individualId.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + + (if (url.asKnown().isPresent) 1 else 0) + + (if (year.asKnown().isPresent) 1 else 0) + /** The type of document. */ class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -288,6 +381,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DocumentRetreiveResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DocumentRetreiveResponse.kt index 4fa2026a..57f278d9 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DocumentRetreiveResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/DocumentRetreiveResponse.kt @@ -61,13 +61,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { w42020 != null -> visitor.visitW42020(w42020) w42005 != null -> visitor.visitW42005(w42005) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -90,6 +89,31 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitW42020(w42020: W42020) = w42020.validity() + + override fun visitW42005(w42005: W42005) = w42005.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -165,16 +189,14 @@ private constructor( when (type) { "w4_2020" -> { - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return DocumentRetreiveResponse(w42020 = it, _json = json) - } + return tryDeserialize(node, jacksonTypeRef())?.let { + DocumentRetreiveResponse(w42020 = it, _json = json) + } ?: DocumentRetreiveResponse(_json = json) } "w4_2005" -> { - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return DocumentRetreiveResponse(w42005 = it, _json = json) - } + return tryDeserialize(node, jacksonTypeRef())?.let { + DocumentRetreiveResponse(w42005 = it, _json = json) + } ?: DocumentRetreiveResponse(_json = json) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentData.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentData.kt index 75f7e6db..b90cc44a 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentData.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentData.kt @@ -11,268 +11,428 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class EmploymentData -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("class_code") - @ExcludeMissing - private val classCode: JsonField = JsonMissing.of(), - @JsonProperty("custom_fields") - @ExcludeMissing - private val customFields: JsonField> = JsonMissing.of(), - @JsonProperty("department") - @ExcludeMissing - private val department: JsonField = JsonMissing.of(), - @JsonProperty("employment") - @ExcludeMissing - private val employment: JsonField = JsonMissing.of(), - @JsonProperty("employment_status") - @ExcludeMissing - private val employmentStatus: JsonField = JsonMissing.of(), - @JsonProperty("end_date") - @ExcludeMissing - private val endDate: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("income") - @ExcludeMissing - private val income: JsonField = JsonMissing.of(), - @JsonProperty("income_history") - @ExcludeMissing - private val incomeHistory: JsonField> = JsonMissing.of(), - @JsonProperty("is_active") - @ExcludeMissing - private val isActive: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), - @JsonProperty("latest_rehire_date") - @ExcludeMissing - private val latestRehireDate: JsonField = JsonMissing.of(), - @JsonProperty("location") - @ExcludeMissing - private val location: JsonField = JsonMissing.of(), - @JsonProperty("manager") - @ExcludeMissing - private val manager: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), - @JsonProperty("source_id") - @ExcludeMissing - private val sourceId: JsonField = JsonMissing.of(), - @JsonProperty("start_date") - @ExcludeMissing - private val startDate: JsonField = JsonMissing.of(), - @JsonProperty("title") @ExcludeMissing private val title: JsonField = JsonMissing.of(), - @JsonProperty("work_id") - @ExcludeMissing - private val workId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val classCode: JsonField, + private val customFields: JsonField>, + private val department: JsonField, + private val employment: JsonField, + private val employmentStatus: JsonField, + private val endDate: JsonField, + private val firstName: JsonField, + private val income: JsonField, + private val incomeHistory: JsonField>, + private val isActive: JsonField, + private val lastName: JsonField, + private val latestRehireDate: JsonField, + private val location: JsonField, + private val manager: JsonField, + private val middleName: JsonField, + private val sourceId: JsonField, + private val startDate: JsonField, + private val title: JsonField, + private val workId: JsonField, + private val additionalProperties: MutableMap, ) { - /** string A stable Finch `id` (UUID v4) for an individual in the company. */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("class_code") @ExcludeMissing classCode: JsonField = JsonMissing.of(), + @JsonProperty("custom_fields") + @ExcludeMissing + customFields: JsonField> = JsonMissing.of(), + @JsonProperty("department") + @ExcludeMissing + department: JsonField = JsonMissing.of(), + @JsonProperty("employment") + @ExcludeMissing + employment: JsonField = JsonMissing.of(), + @JsonProperty("employment_status") + @ExcludeMissing + employmentStatus: JsonField = JsonMissing.of(), + @JsonProperty("end_date") @ExcludeMissing endDate: JsonField = JsonMissing.of(), + @JsonProperty("first_name") @ExcludeMissing firstName: JsonField = JsonMissing.of(), + @JsonProperty("income") @ExcludeMissing income: JsonField = JsonMissing.of(), + @JsonProperty("income_history") + @ExcludeMissing + incomeHistory: JsonField> = JsonMissing.of(), + @JsonProperty("is_active") @ExcludeMissing isActive: JsonField = JsonMissing.of(), + @JsonProperty("last_name") @ExcludeMissing lastName: JsonField = JsonMissing.of(), + @JsonProperty("latest_rehire_date") + @ExcludeMissing + latestRehireDate: JsonField = JsonMissing.of(), + @JsonProperty("location") @ExcludeMissing location: JsonField = JsonMissing.of(), + @JsonProperty("manager") @ExcludeMissing manager: JsonField = JsonMissing.of(), + @JsonProperty("middle_name") + @ExcludeMissing + middleName: JsonField = JsonMissing.of(), + @JsonProperty("source_id") @ExcludeMissing sourceId: JsonField = JsonMissing.of(), + @JsonProperty("start_date") @ExcludeMissing startDate: JsonField = JsonMissing.of(), + @JsonProperty("title") @ExcludeMissing title: JsonField = JsonMissing.of(), + @JsonProperty("work_id") @ExcludeMissing workId: JsonField = JsonMissing.of(), + ) : this( + id, + classCode, + customFields, + department, + employment, + employmentStatus, + endDate, + firstName, + income, + incomeHistory, + isActive, + lastName, + latestRehireDate, + location, + manager, + middleName, + sourceId, + startDate, + title, + workId, + mutableMapOf(), + ) - /** Worker's compensation classification code for this employee */ - fun classCode(): Optional = Optional.ofNullable(classCode.getNullable("class_code")) + /** + * A stable Finch `id` (UUID v4) for an individual in the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Worker's compensation classification code for this employee + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun classCode(): Optional = classCode.getOptional("class_code") /** * Custom fields for the individual. These are fields which are defined by the employer in the * system. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun customFields(): Optional> = - Optional.ofNullable(customFields.getNullable("custom_fields")) + fun customFields(): Optional> = customFields.getOptional("custom_fields") - /** The department object. */ - fun department(): Optional = - Optional.ofNullable(department.getNullable("department")) + /** + * The department object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun department(): Optional = department.getOptional("department") - /** The employment object. */ - fun employment(): Optional = - Optional.ofNullable(employment.getNullable("employment")) + /** + * The employment object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun employment(): Optional = employment.getOptional("employment") /** * The detailed employment status of the individual. Available options: `active`, `deceased`, * `leave`, `onboarding`, `prehire`, `retired`, `terminated`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ fun employmentStatus(): Optional = - Optional.ofNullable(employmentStatus.getNullable("employment_status")) + employmentStatus.getOptional("employment_status") - fun endDate(): Optional = Optional.ofNullable(endDate.getNullable("end_date")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun endDate(): Optional = endDate.getOptional("end_date") - /** The legal first name of the individual. */ - fun firstName(): Optional = Optional.ofNullable(firstName.getNullable("first_name")) + /** + * The legal first name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") /** * The employee's income as reported by the provider. This may not always be annualized income, * but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what information the * provider returns. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun income(): Optional = Optional.ofNullable(income.getNullable("income")) + fun income(): Optional = income.getOptional("income") - /** The array of income history. */ - fun incomeHistory(): Optional> = - Optional.ofNullable(incomeHistory.getNullable("income_history")) + /** + * The array of income history. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun incomeHistory(): Optional> = incomeHistory.getOptional("income_history") - /** `true` if the individual an an active employee or contractor at the company. */ - fun isActive(): Optional = Optional.ofNullable(isActive.getNullable("is_active")) + /** + * `true` if the individual an an active employee or contractor at the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isActive(): Optional = isActive.getOptional("is_active") - /** The legal last name of the individual. */ - fun lastName(): Optional = Optional.ofNullable(lastName.getNullable("last_name")) + /** + * The legal last name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") - fun latestRehireDate(): Optional = - Optional.ofNullable(latestRehireDate.getNullable("latest_rehire_date")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun latestRehireDate(): Optional = latestRehireDate.getOptional("latest_rehire_date") - fun location(): Optional = Optional.ofNullable(location.getNullable("location")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun location(): Optional = location.getOptional("location") - /** The manager object representing the manager of the individual within the org. */ - fun manager(): Optional = Optional.ofNullable(manager.getNullable("manager")) + /** + * The manager object representing the manager of the individual within the org. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun manager(): Optional = manager.getOptional("manager") - /** The legal middle name of the individual. */ - fun middleName(): Optional = Optional.ofNullable(middleName.getNullable("middle_name")) + /** + * The legal middle name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") - /** The source system's unique employment identifier for this individual */ - fun sourceId(): Optional = Optional.ofNullable(sourceId.getNullable("source_id")) + /** + * The source system's unique employment identifier for this individual + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun sourceId(): Optional = sourceId.getOptional("source_id") - fun startDate(): Optional = Optional.ofNullable(startDate.getNullable("start_date")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun startDate(): Optional = startDate.getOptional("start_date") - /** The current title of the individual. */ - fun title(): Optional = Optional.ofNullable(title.getNullable("title")) + /** + * The current title of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun title(): Optional = title.getOptional("title") - /** This field is deprecated in favour of `source_id` */ - @Deprecated("deprecated") - fun workId(): Optional = Optional.ofNullable(workId.getNullable("work_id")) + /** + * This field is deprecated in favour of `source_id` + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + @Deprecated("deprecated") fun workId(): Optional = workId.getOptional("work_id") - /** string A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - /** Worker's compensation classification code for this employee */ + /** + * Returns the raw JSON value of [classCode]. + * + * Unlike [classCode], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("class_code") @ExcludeMissing fun _classCode(): JsonField = classCode /** - * Custom fields for the individual. These are fields which are defined by the employer in the - * system. + * Returns the raw JSON value of [customFields]. + * + * Unlike [customFields], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("custom_fields") @ExcludeMissing fun _customFields(): JsonField> = customFields - /** The department object. */ + /** + * Returns the raw JSON value of [department]. + * + * Unlike [department], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("department") @ExcludeMissing fun _department(): JsonField = department - /** The employment object. */ + /** + * Returns the raw JSON value of [employment]. + * + * Unlike [employment], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("employment") @ExcludeMissing fun _employment(): JsonField = employment /** - * The detailed employment status of the individual. Available options: `active`, `deceased`, - * `leave`, `onboarding`, `prehire`, `retired`, `terminated`. + * Returns the raw JSON value of [employmentStatus]. + * + * Unlike [employmentStatus], this method doesn't throw if the JSON field has an unexpected + * type. */ @JsonProperty("employment_status") @ExcludeMissing fun _employmentStatus(): JsonField = employmentStatus + /** + * Returns the raw JSON value of [endDate]. + * + * Unlike [endDate], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("end_date") @ExcludeMissing fun _endDate(): JsonField = endDate - /** The legal first name of the individual. */ + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName /** - * The employee's income as reported by the provider. This may not always be annualized income, - * but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what information the - * provider returns. + * Returns the raw JSON value of [income]. + * + * Unlike [income], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("income") @ExcludeMissing fun _income(): JsonField = income - /** The array of income history. */ + /** + * Returns the raw JSON value of [incomeHistory]. + * + * Unlike [incomeHistory], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("income_history") @ExcludeMissing fun _incomeHistory(): JsonField> = incomeHistory - /** `true` if the individual an an active employee or contractor at the company. */ + /** + * Returns the raw JSON value of [isActive]. + * + * Unlike [isActive], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("is_active") @ExcludeMissing fun _isActive(): JsonField = isActive - /** The legal last name of the individual. */ + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName + /** + * Returns the raw JSON value of [latestRehireDate]. + * + * Unlike [latestRehireDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("latest_rehire_date") @ExcludeMissing fun _latestRehireDate(): JsonField = latestRehireDate + /** + * Returns the raw JSON value of [location]. + * + * Unlike [location], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("location") @ExcludeMissing fun _location(): JsonField = location - /** The manager object representing the manager of the individual within the org. */ + /** + * Returns the raw JSON value of [manager]. + * + * Unlike [manager], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("manager") @ExcludeMissing fun _manager(): JsonField = manager - /** The legal middle name of the individual. */ + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("middle_name") @ExcludeMissing fun _middleName(): JsonField = middleName - /** The source system's unique employment identifier for this individual */ + /** + * Returns the raw JSON value of [sourceId]. + * + * Unlike [sourceId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("source_id") @ExcludeMissing fun _sourceId(): JsonField = sourceId + /** + * Returns the raw JSON value of [startDate]. + * + * Unlike [startDate], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("start_date") @ExcludeMissing fun _startDate(): JsonField = startDate - /** The current title of the individual. */ + /** + * Returns the raw JSON value of [title]. + * + * Unlike [title], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("title") @ExcludeMissing fun _title(): JsonField = title - /** This field is deprecated in favour of `source_id` */ + /** + * Returns the raw JSON value of [workId]. + * + * Unlike [workId], this method doesn't throw if the JSON field has an unexpected type. + */ @Deprecated("deprecated") @JsonProperty("work_id") @ExcludeMissing fun _workId(): JsonField = workId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): EmploymentData = apply { - if (validated) { - return@apply - } - - id() - classCode() - customFields().ifPresent { it.forEach { it.validate() } } - department().ifPresent { it.validate() } - employment().ifPresent { it.validate() } - employmentStatus() - endDate() - firstName() - income().ifPresent { it.validate() } - incomeHistory().ifPresent { it.forEach { it?.validate() } } - isActive() - lastName() - latestRehireDate() - location().ifPresent { it.validate() } - manager().ifPresent { it.validate() } - middleName() - sourceId() - startDate() - title() - workId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [EmploymentData]. */ @JvmStatic fun builder() = Builder() } @@ -326,19 +486,30 @@ private constructor( additionalProperties = employmentData.additionalProperties.toMutableMap() } - /** string A stable Finch `id` (UUID v4) for an individual in the company. */ + /** A stable Finch `id` (UUID v4) for an individual in the company. */ fun id(id: String) = id(JsonField.of(id)) - /** string A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } /** Worker's compensation classification code for this employee */ fun classCode(classCode: String?) = classCode(JsonField.ofNullable(classCode)) - /** Worker's compensation classification code for this employee */ - fun classCode(classCode: Optional) = classCode(classCode.orElse(null)) + /** Alias for calling [Builder.classCode] with `classCode.orElse(null)`. */ + fun classCode(classCode: Optional) = classCode(classCode.getOrNull()) - /** Worker's compensation classification code for this employee */ + /** + * Sets [Builder.classCode] to an arbitrary JSON value. + * + * You should usually call [Builder.classCode] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun classCode(classCode: JsonField) = apply { this.classCode = classCode } /** @@ -348,54 +519,61 @@ private constructor( fun customFields(customFields: List?) = customFields(JsonField.ofNullable(customFields)) - /** - * Custom fields for the individual. These are fields which are defined by the employer in - * the system. - */ + /** Alias for calling [Builder.customFields] with `customFields.orElse(null)`. */ fun customFields(customFields: Optional>) = - customFields(customFields.orElse(null)) + customFields(customFields.getOrNull()) /** - * Custom fields for the individual. These are fields which are defined by the employer in - * the system. + * Sets [Builder.customFields] to an arbitrary JSON value. + * + * You should usually call [Builder.customFields] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. */ fun customFields(customFields: JsonField>) = apply { this.customFields = customFields.map { it.toMutableList() } } /** - * Custom fields for the individual. These are fields which are defined by the employer in - * the system. + * Adds a single [CustomField] to [customFields]. + * + * @throws IllegalStateException if the field was previously set to a non-list. */ fun addCustomField(customField: CustomField) = apply { customFields = - (customFields ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(customField) + (customFields ?: JsonField.of(mutableListOf())).also { + checkKnown("customFields", it).add(customField) } } /** The department object. */ fun department(department: Department?) = department(JsonField.ofNullable(department)) - /** The department object. */ - fun department(department: Optional) = department(department.orElse(null)) + /** Alias for calling [Builder.department] with `department.orElse(null)`. */ + fun department(department: Optional) = department(department.getOrNull()) - /** The department object. */ + /** + * Sets [Builder.department] to an arbitrary JSON value. + * + * You should usually call [Builder.department] with a well-typed [Department] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun department(department: JsonField) = apply { this.department = department } /** The employment object. */ fun employment(employment: Employment?) = employment(JsonField.ofNullable(employment)) - /** The employment object. */ - fun employment(employment: Optional) = employment(employment.orElse(null)) + /** Alias for calling [Builder.employment] with `employment.orElse(null)`. */ + fun employment(employment: Optional) = employment(employment.getOrNull()) - /** The employment object. */ + /** + * Sets [Builder.employment] to an arbitrary JSON value. + * + * You should usually call [Builder.employment] with a well-typed [Employment] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun employment(employment: JsonField) = apply { this.employment = employment } /** @@ -405,16 +583,16 @@ private constructor( fun employmentStatus(employmentStatus: EmploymentStatus?) = employmentStatus(JsonField.ofNullable(employmentStatus)) - /** - * The detailed employment status of the individual. Available options: `active`, - * `deceased`, `leave`, `onboarding`, `prehire`, `retired`, `terminated`. - */ + /** Alias for calling [Builder.employmentStatus] with `employmentStatus.orElse(null)`. */ fun employmentStatus(employmentStatus: Optional) = - employmentStatus(employmentStatus.orElse(null)) + employmentStatus(employmentStatus.getOrNull()) /** - * The detailed employment status of the individual. Available options: `active`, - * `deceased`, `leave`, `onboarding`, `prehire`, `retired`, `terminated`. + * Sets [Builder.employmentStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.employmentStatus] with a well-typed [EmploymentStatus] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. */ fun employmentStatus(employmentStatus: JsonField) = apply { this.employmentStatus = employmentStatus @@ -422,17 +600,30 @@ private constructor( fun endDate(endDate: String?) = endDate(JsonField.ofNullable(endDate)) - fun endDate(endDate: Optional) = endDate(endDate.orElse(null)) + /** Alias for calling [Builder.endDate] with `endDate.orElse(null)`. */ + fun endDate(endDate: Optional) = endDate(endDate.getOrNull()) + /** + * Sets [Builder.endDate] to an arbitrary JSON value. + * + * You should usually call [Builder.endDate] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun endDate(endDate: JsonField) = apply { this.endDate = endDate } /** The legal first name of the individual. */ fun firstName(firstName: String?) = firstName(JsonField.ofNullable(firstName)) - /** The legal first name of the individual. */ - fun firstName(firstName: Optional) = firstName(firstName.orElse(null)) + /** Alias for calling [Builder.firstName] with `firstName.orElse(null)`. */ + fun firstName(firstName: Optional) = firstName(firstName.getOrNull()) - /** The legal first name of the individual. */ + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun firstName(firstName: JsonField) = apply { this.firstName = firstName } /** @@ -442,17 +633,14 @@ private constructor( */ fun income(income: Income?) = income(JsonField.ofNullable(income)) - /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. - */ - fun income(income: Optional) = income(income.orElse(null)) + /** Alias for calling [Builder.income] with `income.orElse(null)`. */ + fun income(income: Optional) = income(income.getOrNull()) /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. + * Sets [Builder.income] to an arbitrary JSON value. + * + * You should usually call [Builder.income] with a well-typed [Income] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun income(income: JsonField) = apply { this.income = income } @@ -460,116 +648,184 @@ private constructor( fun incomeHistory(incomeHistory: List?) = incomeHistory(JsonField.ofNullable(incomeHistory)) - /** The array of income history. */ + /** Alias for calling [Builder.incomeHistory] with `incomeHistory.orElse(null)`. */ fun incomeHistory(incomeHistory: Optional>) = - incomeHistory(incomeHistory.orElse(null)) + incomeHistory(incomeHistory.getOrNull()) - /** The array of income history. */ + /** + * Sets [Builder.incomeHistory] to an arbitrary JSON value. + * + * You should usually call [Builder.incomeHistory] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun incomeHistory(incomeHistory: JsonField>) = apply { this.incomeHistory = incomeHistory.map { it.toMutableList() } } - /** The array of income history. */ + /** + * Adds a single [Income] to [Builder.incomeHistory]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addIncomeHistory(incomeHistory: Income) = apply { this.incomeHistory = - (this.incomeHistory ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(incomeHistory) + (this.incomeHistory ?: JsonField.of(mutableListOf())).also { + checkKnown("incomeHistory", it).add(incomeHistory) } } /** `true` if the individual an an active employee or contractor at the company. */ fun isActive(isActive: Boolean?) = isActive(JsonField.ofNullable(isActive)) - /** `true` if the individual an an active employee or contractor at the company. */ + /** + * Alias for [Builder.isActive]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun isActive(isActive: Boolean) = isActive(isActive as Boolean?) - /** `true` if the individual an an active employee or contractor at the company. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun isActive(isActive: Optional) = isActive(isActive.orElse(null) as Boolean?) + /** Alias for calling [Builder.isActive] with `isActive.orElse(null)`. */ + fun isActive(isActive: Optional) = isActive(isActive.getOrNull()) - /** `true` if the individual an an active employee or contractor at the company. */ + /** + * Sets [Builder.isActive] to an arbitrary JSON value. + * + * You should usually call [Builder.isActive] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun isActive(isActive: JsonField) = apply { this.isActive = isActive } /** The legal last name of the individual. */ fun lastName(lastName: String?) = lastName(JsonField.ofNullable(lastName)) - /** The legal last name of the individual. */ - fun lastName(lastName: Optional) = lastName(lastName.orElse(null)) + /** Alias for calling [Builder.lastName] with `lastName.orElse(null)`. */ + fun lastName(lastName: Optional) = lastName(lastName.getOrNull()) - /** The legal last name of the individual. */ + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun lastName(lastName: JsonField) = apply { this.lastName = lastName } fun latestRehireDate(latestRehireDate: String?) = latestRehireDate(JsonField.ofNullable(latestRehireDate)) + /** Alias for calling [Builder.latestRehireDate] with `latestRehireDate.orElse(null)`. */ fun latestRehireDate(latestRehireDate: Optional) = - latestRehireDate(latestRehireDate.orElse(null)) + latestRehireDate(latestRehireDate.getOrNull()) + /** + * Sets [Builder.latestRehireDate] to an arbitrary JSON value. + * + * You should usually call [Builder.latestRehireDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun latestRehireDate(latestRehireDate: JsonField) = apply { this.latestRehireDate = latestRehireDate } fun location(location: Location?) = location(JsonField.ofNullable(location)) - fun location(location: Optional) = location(location.orElse(null)) + /** Alias for calling [Builder.location] with `location.orElse(null)`. */ + fun location(location: Optional) = location(location.getOrNull()) + /** + * Sets [Builder.location] to an arbitrary JSON value. + * + * You should usually call [Builder.location] with a well-typed [Location] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun location(location: JsonField) = apply { this.location = location } /** The manager object representing the manager of the individual within the org. */ fun manager(manager: Manager?) = manager(JsonField.ofNullable(manager)) - /** The manager object representing the manager of the individual within the org. */ - fun manager(manager: Optional) = manager(manager.orElse(null)) + /** Alias for calling [Builder.manager] with `manager.orElse(null)`. */ + fun manager(manager: Optional) = manager(manager.getOrNull()) - /** The manager object representing the manager of the individual within the org. */ + /** + * Sets [Builder.manager] to an arbitrary JSON value. + * + * You should usually call [Builder.manager] with a well-typed [Manager] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun manager(manager: JsonField) = apply { this.manager = manager } /** The legal middle name of the individual. */ fun middleName(middleName: String?) = middleName(JsonField.ofNullable(middleName)) - /** The legal middle name of the individual. */ - fun middleName(middleName: Optional) = middleName(middleName.orElse(null)) + /** Alias for calling [Builder.middleName] with `middleName.orElse(null)`. */ + fun middleName(middleName: Optional) = middleName(middleName.getOrNull()) - /** The legal middle name of the individual. */ + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun middleName(middleName: JsonField) = apply { this.middleName = middleName } /** The source system's unique employment identifier for this individual */ fun sourceId(sourceId: String?) = sourceId(JsonField.ofNullable(sourceId)) - /** The source system's unique employment identifier for this individual */ - fun sourceId(sourceId: Optional) = sourceId(sourceId.orElse(null)) + /** Alias for calling [Builder.sourceId] with `sourceId.orElse(null)`. */ + fun sourceId(sourceId: Optional) = sourceId(sourceId.getOrNull()) - /** The source system's unique employment identifier for this individual */ + /** + * Sets [Builder.sourceId] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun sourceId(sourceId: JsonField) = apply { this.sourceId = sourceId } fun startDate(startDate: String?) = startDate(JsonField.ofNullable(startDate)) - fun startDate(startDate: Optional) = startDate(startDate.orElse(null)) + /** Alias for calling [Builder.startDate] with `startDate.orElse(null)`. */ + fun startDate(startDate: Optional) = startDate(startDate.getOrNull()) + /** + * Sets [Builder.startDate] to an arbitrary JSON value. + * + * You should usually call [Builder.startDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun startDate(startDate: JsonField) = apply { this.startDate = startDate } /** The current title of the individual. */ fun title(title: String?) = title(JsonField.ofNullable(title)) - /** The current title of the individual. */ - fun title(title: Optional) = title(title.orElse(null)) + /** Alias for calling [Builder.title] with `title.orElse(null)`. */ + fun title(title: Optional) = title(title.getOrNull()) - /** The current title of the individual. */ + /** + * Sets [Builder.title] to an arbitrary JSON value. + * + * You should usually call [Builder.title] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun title(title: JsonField) = apply { this.title = title } /** This field is deprecated in favour of `source_id` */ @Deprecated("deprecated") fun workId(workId: String?) = workId(JsonField.ofNullable(workId)) - /** This field is deprecated in favour of `source_id` */ - @Deprecated("deprecated") fun workId(workId: Optional) = workId(workId.orElse(null)) + /** Alias for calling [Builder.workId] with `workId.orElse(null)`. */ + @Deprecated("deprecated") fun workId(workId: Optional) = workId(workId.getOrNull()) - /** This field is deprecated in favour of `source_id` */ + /** + * Sets [Builder.workId] to an arbitrary JSON value. + * + * You should usually call [Builder.workId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ @Deprecated("deprecated") fun workId(workId: JsonField) = apply { this.workId = workId } @@ -592,6 +848,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [EmploymentData]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): EmploymentData = EmploymentData( id, @@ -614,47 +875,119 @@ private constructor( startDate, title, workId, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): EmploymentData = apply { + if (validated) { + return@apply + } + + id() + classCode() + customFields().ifPresent { it.forEach { it.validate() } } + department().ifPresent { it.validate() } + employment().ifPresent { it.validate() } + employmentStatus().ifPresent { it.validate() } + endDate() + firstName() + income().ifPresent { it.validate() } + incomeHistory().ifPresent { it.forEach { it?.validate() } } + isActive() + lastName() + latestRehireDate() + location().ifPresent { it.validate() } + manager().ifPresent { it.validate() } + middleName() + sourceId() + startDate() + title() + workId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (classCode.asKnown().isPresent) 1 else 0) + + (customFields.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (department.asKnown().getOrNull()?.validity() ?: 0) + + (employment.asKnown().getOrNull()?.validity() ?: 0) + + (employmentStatus.asKnown().getOrNull()?.validity() ?: 0) + + (if (endDate.asKnown().isPresent) 1 else 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (income.asKnown().getOrNull()?.validity() ?: 0) + + (incomeHistory.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (isActive.asKnown().isPresent) 1 else 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (if (latestRehireDate.asKnown().isPresent) 1 else 0) + + (location.asKnown().getOrNull()?.validity() ?: 0) + + (manager.asKnown().getOrNull()?.validity() ?: 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + + (if (sourceId.asKnown().isPresent) 1 else 0) + + (if (startDate.asKnown().isPresent) 1 else 0) + + (if (title.asKnown().isPresent) 1 else 0) + + (if (workId.asKnown().isPresent) 1 else 0) + class CustomField - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("value") @ExcludeMissing private val value: JsonValue = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val value: JsonValue, + private val additionalProperties: MutableMap, ) { - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonValue = JsonMissing.of(), + ) : this(name, value, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") @JsonProperty("value") @ExcludeMissing fun _value(): JsonValue = value + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): CustomField = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [CustomField]. */ @JvmStatic fun builder() = Builder() } @@ -674,6 +1007,13 @@ private constructor( fun name(name: String) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } fun value(value: JsonValue) = apply { this.value = value } @@ -697,9 +1037,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): CustomField = CustomField(name, value, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [CustomField]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomField = CustomField(name, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CustomField = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -719,42 +1091,47 @@ private constructor( } /** The department object. */ - @NoAutoDetect class Department - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - /** The name of the department associated with the individual. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) + + /** + * The name of the department associated with the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** The name of the department associated with the individual. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Department = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Department]. */ @JvmStatic fun builder() = Builder() } @@ -773,10 +1150,16 @@ private constructor( /** The name of the department associated with the individual. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The name of the department associated with the individual. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The name of the department associated with the individual. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = apply { @@ -798,9 +1181,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Department = Department(name, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Department]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Department = Department(name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Department = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -820,56 +1235,65 @@ private constructor( } /** The employment object. */ - @NoAutoDetect class Employment - @JsonCreator private constructor( - @JsonProperty("subtype") - @ExcludeMissing - private val subtype: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val subtype: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("subtype") @ExcludeMissing subtype: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(subtype, type, mutableMapOf()) + /** * The secondary employment type of the individual. Options: `full_time`, `part_time`, * `intern`, `temp`, `seasonal` and `individual_contractor`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun subtype(): Optional = Optional.ofNullable(subtype.getNullable("subtype")) + fun subtype(): Optional = subtype.getOptional("subtype") - /** The main employment type of the individual. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The main employment type of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") /** - * The secondary employment type of the individual. Options: `full_time`, `part_time`, - * `intern`, `temp`, `seasonal` and `individual_contractor`. + * Returns the raw JSON value of [subtype]. + * + * Unlike [subtype], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype - /** The main employment type of the individual. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Employment = apply { - if (validated) { - return@apply - } - - subtype() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Employment]. */ @JvmStatic fun builder() = Builder() } @@ -893,25 +1317,31 @@ private constructor( */ fun subtype(subtype: Subtype?) = subtype(JsonField.ofNullable(subtype)) - /** - * The secondary employment type of the individual. Options: `full_time`, `part_time`, - * `intern`, `temp`, `seasonal` and `individual_contractor`. - */ - fun subtype(subtype: Optional) = subtype(subtype.orElse(null)) + /** Alias for calling [Builder.subtype] with `subtype.orElse(null)`. */ + fun subtype(subtype: Optional) = subtype(subtype.getOrNull()) /** - * The secondary employment type of the individual. Options: `full_time`, `part_time`, - * `intern`, `temp`, `seasonal` and `individual_contractor`. + * Sets [Builder.subtype] to an arbitrary JSON value. + * + * You should usually call [Builder.subtype] with a well-typed [Subtype] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun subtype(subtype: JsonField) = apply { this.subtype = subtype } /** The main employment type of the individual. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** The main employment type of the individual. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** The main employment type of the individual. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -933,9 +1363,45 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Employment = Employment(subtype, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Employment]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Employment = Employment(subtype, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Employment = apply { + if (validated) { + return@apply + } + + subtype().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (subtype.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + /** * The secondary employment type of the individual. Options: `full_time`, `part_time`, * `intern`, `temp`, `seasonal` and `individual_contractor`. @@ -1054,6 +1520,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Subtype = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1155,6 +1648,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1308,6 +1828,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EmploymentStatus = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1322,40 +1869,47 @@ private constructor( } /** The manager object representing the manager of the individual within the org. */ - @NoAutoDetect class Manager - @JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val additionalProperties: MutableMap, ) { - /** A stable Finch `id` (UUID v4) for an individual in the company. */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of() + ) : this(id, mutableMapOf()) - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * A stable Finch `id` (UUID v4) for an individual in the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Manager = apply { - if (validated) { - return@apply - } - - id() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Manager]. */ @JvmStatic fun builder() = Builder() } @@ -1374,7 +1928,13 @@ private constructor( /** A stable Finch `id` (UUID v4) for an individual in the company. */ fun id(id: String) = id(JsonField.of(id)) - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun id(id: JsonField) = apply { this.id = id } fun additionalProperties(additionalProperties: Map) = apply { @@ -1396,9 +1956,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Manager = Manager(id, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Manager]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Manager = Manager(id, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Manager = apply { + if (validated) { + return@apply + } + + id() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (id.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentDataResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentDataResponse.kt index 28da48df..4f8bcca8 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentDataResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentDataResponse.kt @@ -10,62 +10,87 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class EmploymentDataResponse -@JsonCreator private constructor( - @JsonProperty("body") - @ExcludeMissing - private val body: JsonField = JsonMissing.of(), - @JsonProperty("code") @ExcludeMissing private val code: JsonField = JsonMissing.of(), - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val body: JsonField, + private val code: JsonField, + private val individualId: JsonField, + private val additionalProperties: MutableMap, ) { - fun body(): Optional = Optional.ofNullable(body.getNullable("body")) - - fun code(): Optional = Optional.ofNullable(code.getNullable("code")) - - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) - + @JsonCreator + private constructor( + @JsonProperty("body") @ExcludeMissing body: JsonField = JsonMissing.of(), + @JsonProperty("code") @ExcludeMissing code: JsonField = JsonMissing.of(), + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of(), + ) : this(body, code, individualId, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun body(): Optional = body.getOptional("body") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun code(): Optional = code.getOptional("code") + + /** + * A stable Finch `id` (UUID v4) for an individual in the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") + + /** + * Returns the raw JSON value of [body]. + * + * Unlike [body], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("body") @ExcludeMissing fun _body(): JsonField = body + /** + * Returns the raw JSON value of [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): EmploymentDataResponse = apply { - if (validated) { - return@apply - } - - body().ifPresent { it.validate() } - code() - individualId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [EmploymentDataResponse]. */ @JvmStatic fun builder() = Builder() } @@ -87,14 +112,35 @@ private constructor( fun body(body: EmploymentData) = body(JsonField.of(body)) + /** + * Sets [Builder.body] to an arbitrary JSON value. + * + * You should usually call [Builder.body] with a well-typed [EmploymentData] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun body(body: JsonField) = apply { this.body = body } fun code(code: Long) = code(JsonField.of(code)) + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun code(code: JsonField) = apply { this.code = code } + /** A stable Finch `id` (UUID v4) for an individual in the company. */ fun individualId(individualId: String) = individualId(JsonField.of(individualId)) + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -118,10 +164,47 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [EmploymentDataResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): EmploymentDataResponse = - EmploymentDataResponse(body, code, individualId, additionalProperties.toImmutable()) + EmploymentDataResponse(body, code, individualId, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): EmploymentDataResponse = apply { + if (validated) { + return@apply + } + + body().ifPresent { it.validate() } + code() + individualId() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (body.asKnown().getOrNull()?.validity() ?: 0) + + (if (code.asKnown().isPresent) 1 else 0) + + (if (individualId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentEvent.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentEvent.kt index b67ef641..94850259 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentEvent.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentEvent.kt @@ -11,57 +11,85 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class EmploymentEvent -@JsonCreator private constructor( - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("data") @ExcludeMissing private val data: JsonField = JsonMissing.of(), - @JsonProperty("event_type") - @ExcludeMissing - private val eventType: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accountId: JsonField, + private val companyId: JsonField, + private val connectionId: JsonField, + private val data: JsonField, + private val eventType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("event_type") + @ExcludeMissing + eventType: JsonField = JsonMissing.of(), + ) : this(accountId, companyId, connectionId, data, eventType, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder() + .accountId(accountId) + .companyId(companyId) + .connectionId(connectionId) + .build() + /** * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") /** * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") - /** Unique Finch ID of the connection associated with the webhook event. */ - fun connectionId(): Optional = - Optional.ofNullable(connectionId.getNullable("connection_id")) + /** + * Unique Finch ID of the connection associated with the webhook event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun connectionId(): Optional = connectionId.getOptional("connection_id") - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") - fun eventType(): Optional = Optional.ofNullable(eventType.getNullable("event_type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun eventType(): Optional = eventType.getOptional("event_type") /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("account_id") @@ -69,53 +97,61 @@ private constructor( fun _accountId(): JsonField = accountId /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [eventType]. + * + * Unlike [eventType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("event_type") @ExcludeMissing fun _eventType(): JsonField = eventType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBaseWebhookEvent(): BaseWebhookEvent = - BaseWebhookEvent.builder() - .accountId(accountId) - .companyId(companyId) - .connectionId(connectionId) - .build() - - private var validated: Boolean = false - - fun validate(): EmploymentEvent = apply { - if (validated) { - return@apply - } - - accountId() - companyId() - connectionId() - data().ifPresent { it.validate() } - eventType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [EmploymentEvent]. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -147,8 +183,11 @@ private constructor( fun accountId(accountId: String) = accountId(JsonField.of(accountId)) /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } @@ -161,8 +200,11 @@ private constructor( fun companyId(companyId: String) = companyId(JsonField.of(companyId)) /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } @@ -170,17 +212,36 @@ private constructor( /** Unique Finch ID of the connection associated with the webhook event. */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } fun data(data: Data) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun eventType(eventType: EventType) = eventType(JsonField.of(eventType)) + /** + * Sets [Builder.eventType] to an arbitrary JSON value. + * + * You should usually call [Builder.eventType] with a well-typed [EventType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun eventType(eventType: JsonField) = apply { this.eventType = eventType } fun additionalProperties(additionalProperties: Map) = apply { @@ -202,6 +263,19 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [EmploymentEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): EmploymentEvent = EmploymentEvent( checkRequired("accountId", accountId), @@ -209,49 +283,92 @@ private constructor( connectionId, data, eventType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): EmploymentEvent = apply { + if (validated) { + return@apply + } + + accountId() + companyId() + connectionId() + data().ifPresent { it.validate() } + eventType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountId.asKnown().isPresent) 1 else 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (eventType.asKnown().getOrNull()?.validity() ?: 0) + class Data - @JsonCreator private constructor( - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val individualId: JsonField, + private val additionalProperties: MutableMap, ) { - /** The ID of the individual related to the event. */ - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) + @JsonCreator + private constructor( + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of() + ) : this(individualId, mutableMapOf()) + + /** + * The ID of the individual related to the event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") - /** The ID of the individual related to the event. */ + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Data = apply { - if (validated) { - return@apply - } - - individualId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Data]. */ @JvmStatic fun builder() = Builder() } @@ -270,7 +387,13 @@ private constructor( /** The ID of the individual related to the event. */ fun individualId(individualId: String) = individualId(JsonField.of(individualId)) - /** The ID of the individual related to the event. */ + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -294,9 +417,42 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Data = Data(individualId, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Data = Data(individualId, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + individualId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (individualId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -407,6 +563,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EventType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentUpdateResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentUpdateResponse.kt index f900c3bb..bbd6076b 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentUpdateResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EmploymentUpdateResponse.kt @@ -11,248 +11,406 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class EmploymentUpdateResponse -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("class_code") - @ExcludeMissing - private val classCode: JsonField = JsonMissing.of(), - @JsonProperty("custom_fields") - @ExcludeMissing - private val customFields: JsonField> = JsonMissing.of(), - @JsonProperty("department") - @ExcludeMissing - private val department: JsonField = JsonMissing.of(), - @JsonProperty("employment") - @ExcludeMissing - private val employment: JsonField = JsonMissing.of(), - @JsonProperty("employment_status") - @ExcludeMissing - private val employmentStatus: JsonField = JsonMissing.of(), - @JsonProperty("end_date") - @ExcludeMissing - private val endDate: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("income") - @ExcludeMissing - private val income: JsonField = JsonMissing.of(), - @JsonProperty("income_history") - @ExcludeMissing - private val incomeHistory: JsonField> = JsonMissing.of(), - @JsonProperty("is_active") - @ExcludeMissing - private val isActive: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), - @JsonProperty("latest_rehire_date") - @ExcludeMissing - private val latestRehireDate: JsonField = JsonMissing.of(), - @JsonProperty("location") - @ExcludeMissing - private val location: JsonField = JsonMissing.of(), - @JsonProperty("manager") - @ExcludeMissing - private val manager: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), - @JsonProperty("source_id") - @ExcludeMissing - private val sourceId: JsonField = JsonMissing.of(), - @JsonProperty("start_date") - @ExcludeMissing - private val startDate: JsonField = JsonMissing.of(), - @JsonProperty("title") @ExcludeMissing private val title: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val classCode: JsonField, + private val customFields: JsonField>, + private val department: JsonField, + private val employment: JsonField, + private val employmentStatus: JsonField, + private val endDate: JsonField, + private val firstName: JsonField, + private val income: JsonField, + private val incomeHistory: JsonField>, + private val isActive: JsonField, + private val lastName: JsonField, + private val latestRehireDate: JsonField, + private val location: JsonField, + private val manager: JsonField, + private val middleName: JsonField, + private val sourceId: JsonField, + private val startDate: JsonField, + private val title: JsonField, + private val additionalProperties: MutableMap, ) { - /** A stable Finch `id` (UUID v4) for an individual in the company. */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("class_code") @ExcludeMissing classCode: JsonField = JsonMissing.of(), + @JsonProperty("custom_fields") + @ExcludeMissing + customFields: JsonField> = JsonMissing.of(), + @JsonProperty("department") + @ExcludeMissing + department: JsonField = JsonMissing.of(), + @JsonProperty("employment") + @ExcludeMissing + employment: JsonField = JsonMissing.of(), + @JsonProperty("employment_status") + @ExcludeMissing + employmentStatus: JsonField = JsonMissing.of(), + @JsonProperty("end_date") @ExcludeMissing endDate: JsonField = JsonMissing.of(), + @JsonProperty("first_name") @ExcludeMissing firstName: JsonField = JsonMissing.of(), + @JsonProperty("income") @ExcludeMissing income: JsonField = JsonMissing.of(), + @JsonProperty("income_history") + @ExcludeMissing + incomeHistory: JsonField> = JsonMissing.of(), + @JsonProperty("is_active") @ExcludeMissing isActive: JsonField = JsonMissing.of(), + @JsonProperty("last_name") @ExcludeMissing lastName: JsonField = JsonMissing.of(), + @JsonProperty("latest_rehire_date") + @ExcludeMissing + latestRehireDate: JsonField = JsonMissing.of(), + @JsonProperty("location") @ExcludeMissing location: JsonField = JsonMissing.of(), + @JsonProperty("manager") @ExcludeMissing manager: JsonField = JsonMissing.of(), + @JsonProperty("middle_name") + @ExcludeMissing + middleName: JsonField = JsonMissing.of(), + @JsonProperty("source_id") @ExcludeMissing sourceId: JsonField = JsonMissing.of(), + @JsonProperty("start_date") @ExcludeMissing startDate: JsonField = JsonMissing.of(), + @JsonProperty("title") @ExcludeMissing title: JsonField = JsonMissing.of(), + ) : this( + id, + classCode, + customFields, + department, + employment, + employmentStatus, + endDate, + firstName, + income, + incomeHistory, + isActive, + lastName, + latestRehireDate, + location, + manager, + middleName, + sourceId, + startDate, + title, + mutableMapOf(), + ) + + /** + * A stable Finch `id` (UUID v4) for an individual in the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") - /** Worker's compensation classification code for this employee */ - fun classCode(): Optional = Optional.ofNullable(classCode.getNullable("class_code")) + /** + * Worker's compensation classification code for this employee + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun classCode(): Optional = classCode.getOptional("class_code") /** * Custom fields for the individual. These are fields which are defined by the employer in the * system. Custom fields are not currently supported for assisted connections. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun customFields(): Optional> = - Optional.ofNullable(customFields.getNullable("custom_fields")) + fun customFields(): Optional> = customFields.getOptional("custom_fields") - /** The department object. */ - fun department(): Optional = - Optional.ofNullable(department.getNullable("department")) + /** + * The department object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun department(): Optional = department.getOptional("department") - /** The employment object. */ - fun employment(): Optional = - Optional.ofNullable(employment.getNullable("employment")) + /** + * The employment object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun employment(): Optional = employment.getOptional("employment") - /** The detailed employment status of the individual. */ + /** + * The detailed employment status of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun employmentStatus(): Optional = - Optional.ofNullable(employmentStatus.getNullable("employment_status")) + employmentStatus.getOptional("employment_status") - fun endDate(): Optional = Optional.ofNullable(endDate.getNullable("end_date")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun endDate(): Optional = endDate.getOptional("end_date") - /** The legal first name of the individual. */ - fun firstName(): Optional = Optional.ofNullable(firstName.getNullable("first_name")) + /** + * The legal first name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") /** * The employee's income as reported by the provider. This may not always be annualized income, * but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what information the * provider returns. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun income(): Optional = Optional.ofNullable(income.getNullable("income")) + fun income(): Optional = income.getOptional("income") - /** The array of income history. */ - fun incomeHistory(): Optional> = - Optional.ofNullable(incomeHistory.getNullable("income_history")) + /** + * The array of income history. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun incomeHistory(): Optional> = incomeHistory.getOptional("income_history") - /** `true` if the individual an an active employee or contractor at the company. */ - fun isActive(): Optional = Optional.ofNullable(isActive.getNullable("is_active")) + /** + * `true` if the individual an an active employee or contractor at the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isActive(): Optional = isActive.getOptional("is_active") - /** The legal last name of the individual. */ - fun lastName(): Optional = Optional.ofNullable(lastName.getNullable("last_name")) + /** + * The legal last name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") - fun latestRehireDate(): Optional = - Optional.ofNullable(latestRehireDate.getNullable("latest_rehire_date")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun latestRehireDate(): Optional = latestRehireDate.getOptional("latest_rehire_date") - fun location(): Optional = Optional.ofNullable(location.getNullable("location")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun location(): Optional = location.getOptional("location") - /** The manager object representing the manager of the individual within the org. */ - fun manager(): Optional = Optional.ofNullable(manager.getNullable("manager")) + /** + * The manager object representing the manager of the individual within the org. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun manager(): Optional = manager.getOptional("manager") - /** The legal middle name of the individual. */ - fun middleName(): Optional = Optional.ofNullable(middleName.getNullable("middle_name")) + /** + * The legal middle name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") - /** The source system's unique employment identifier for this individual */ - fun sourceId(): Optional = Optional.ofNullable(sourceId.getNullable("source_id")) + /** + * The source system's unique employment identifier for this individual + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun sourceId(): Optional = sourceId.getOptional("source_id") - fun startDate(): Optional = Optional.ofNullable(startDate.getNullable("start_date")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun startDate(): Optional = startDate.getOptional("start_date") - /** The current title of the individual. */ - fun title(): Optional = Optional.ofNullable(title.getNullable("title")) + /** + * The current title of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun title(): Optional = title.getOptional("title") - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - /** Worker's compensation classification code for this employee */ + /** + * Returns the raw JSON value of [classCode]. + * + * Unlike [classCode], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("class_code") @ExcludeMissing fun _classCode(): JsonField = classCode /** - * Custom fields for the individual. These are fields which are defined by the employer in the - * system. Custom fields are not currently supported for assisted connections. + * Returns the raw JSON value of [customFields]. + * + * Unlike [customFields], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("custom_fields") @ExcludeMissing fun _customFields(): JsonField> = customFields - /** The department object. */ + /** + * Returns the raw JSON value of [department]. + * + * Unlike [department], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("department") @ExcludeMissing fun _department(): JsonField = department - /** The employment object. */ + /** + * Returns the raw JSON value of [employment]. + * + * Unlike [employment], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("employment") @ExcludeMissing fun _employment(): JsonField = employment - /** The detailed employment status of the individual. */ + /** + * Returns the raw JSON value of [employmentStatus]. + * + * Unlike [employmentStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("employment_status") @ExcludeMissing fun _employmentStatus(): JsonField = employmentStatus + /** + * Returns the raw JSON value of [endDate]. + * + * Unlike [endDate], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("end_date") @ExcludeMissing fun _endDate(): JsonField = endDate - /** The legal first name of the individual. */ + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName /** - * The employee's income as reported by the provider. This may not always be annualized income, - * but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what information the - * provider returns. + * Returns the raw JSON value of [income]. + * + * Unlike [income], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("income") @ExcludeMissing fun _income(): JsonField = income - /** The array of income history. */ + /** + * Returns the raw JSON value of [incomeHistory]. + * + * Unlike [incomeHistory], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("income_history") @ExcludeMissing fun _incomeHistory(): JsonField> = incomeHistory - /** `true` if the individual an an active employee or contractor at the company. */ + /** + * Returns the raw JSON value of [isActive]. + * + * Unlike [isActive], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("is_active") @ExcludeMissing fun _isActive(): JsonField = isActive - /** The legal last name of the individual. */ + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName + /** + * Returns the raw JSON value of [latestRehireDate]. + * + * Unlike [latestRehireDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("latest_rehire_date") @ExcludeMissing fun _latestRehireDate(): JsonField = latestRehireDate + /** + * Returns the raw JSON value of [location]. + * + * Unlike [location], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("location") @ExcludeMissing fun _location(): JsonField = location - /** The manager object representing the manager of the individual within the org. */ + /** + * Returns the raw JSON value of [manager]. + * + * Unlike [manager], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("manager") @ExcludeMissing fun _manager(): JsonField = manager - /** The legal middle name of the individual. */ + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("middle_name") @ExcludeMissing fun _middleName(): JsonField = middleName - /** The source system's unique employment identifier for this individual */ + /** + * Returns the raw JSON value of [sourceId]. + * + * Unlike [sourceId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("source_id") @ExcludeMissing fun _sourceId(): JsonField = sourceId + /** + * Returns the raw JSON value of [startDate]. + * + * Unlike [startDate], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("start_date") @ExcludeMissing fun _startDate(): JsonField = startDate - /** The current title of the individual. */ + /** + * Returns the raw JSON value of [title]. + * + * Unlike [title], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("title") @ExcludeMissing fun _title(): JsonField = title + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): EmploymentUpdateResponse = apply { - if (validated) { - return@apply - } - - id() - classCode() - customFields().ifPresent { it.forEach { it.validate() } } - department().ifPresent { it.validate() } - employment().ifPresent { it.validate() } - employmentStatus() - endDate() - firstName() - income().ifPresent { it.validate() } - incomeHistory().ifPresent { it.forEach { it?.validate() } } - isActive() - lastName() - latestRehireDate() - location().ifPresent { it.validate() } - manager().ifPresent { it.validate() } - middleName() - sourceId() - startDate() - title() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [EmploymentUpdateResponse]. */ @JvmStatic fun builder() = Builder() } @@ -307,16 +465,27 @@ private constructor( /** A stable Finch `id` (UUID v4) for an individual in the company. */ fun id(id: String) = id(JsonField.of(id)) - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } /** Worker's compensation classification code for this employee */ fun classCode(classCode: String?) = classCode(JsonField.ofNullable(classCode)) - /** Worker's compensation classification code for this employee */ - fun classCode(classCode: Optional) = classCode(classCode.orElse(null)) + /** Alias for calling [Builder.classCode] with `classCode.orElse(null)`. */ + fun classCode(classCode: Optional) = classCode(classCode.getOrNull()) - /** Worker's compensation classification code for this employee */ + /** + * Sets [Builder.classCode] to an arbitrary JSON value. + * + * You should usually call [Builder.classCode] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun classCode(classCode: JsonField) = apply { this.classCode = classCode } /** @@ -326,74 +495,103 @@ private constructor( fun customFields(customFields: List) = customFields(JsonField.of(customFields)) /** - * Custom fields for the individual. These are fields which are defined by the employer in - * the system. Custom fields are not currently supported for assisted connections. + * Sets [Builder.customFields] to an arbitrary JSON value. + * + * You should usually call [Builder.customFields] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. */ fun customFields(customFields: JsonField>) = apply { this.customFields = customFields.map { it.toMutableList() } } /** - * Custom fields for the individual. These are fields which are defined by the employer in - * the system. Custom fields are not currently supported for assisted connections. + * Adds a single [CustomField] to [customFields]. + * + * @throws IllegalStateException if the field was previously set to a non-list. */ fun addCustomField(customField: CustomField) = apply { customFields = - (customFields ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(customField) + (customFields ?: JsonField.of(mutableListOf())).also { + checkKnown("customFields", it).add(customField) } } /** The department object. */ fun department(department: Department?) = department(JsonField.ofNullable(department)) - /** The department object. */ - fun department(department: Optional) = department(department.orElse(null)) + /** Alias for calling [Builder.department] with `department.orElse(null)`. */ + fun department(department: Optional) = department(department.getOrNull()) - /** The department object. */ + /** + * Sets [Builder.department] to an arbitrary JSON value. + * + * You should usually call [Builder.department] with a well-typed [Department] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun department(department: JsonField) = apply { this.department = department } /** The employment object. */ fun employment(employment: Employment?) = employment(JsonField.ofNullable(employment)) - /** The employment object. */ - fun employment(employment: Optional) = employment(employment.orElse(null)) + /** Alias for calling [Builder.employment] with `employment.orElse(null)`. */ + fun employment(employment: Optional) = employment(employment.getOrNull()) - /** The employment object. */ + /** + * Sets [Builder.employment] to an arbitrary JSON value. + * + * You should usually call [Builder.employment] with a well-typed [Employment] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun employment(employment: JsonField) = apply { this.employment = employment } /** The detailed employment status of the individual. */ fun employmentStatus(employmentStatus: EmploymentStatus?) = employmentStatus(JsonField.ofNullable(employmentStatus)) - /** The detailed employment status of the individual. */ + /** Alias for calling [Builder.employmentStatus] with `employmentStatus.orElse(null)`. */ fun employmentStatus(employmentStatus: Optional) = - employmentStatus(employmentStatus.orElse(null)) + employmentStatus(employmentStatus.getOrNull()) - /** The detailed employment status of the individual. */ + /** + * Sets [Builder.employmentStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.employmentStatus] with a well-typed [EmploymentStatus] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun employmentStatus(employmentStatus: JsonField) = apply { this.employmentStatus = employmentStatus } fun endDate(endDate: String?) = endDate(JsonField.ofNullable(endDate)) - fun endDate(endDate: Optional) = endDate(endDate.orElse(null)) + /** Alias for calling [Builder.endDate] with `endDate.orElse(null)`. */ + fun endDate(endDate: Optional) = endDate(endDate.getOrNull()) + /** + * Sets [Builder.endDate] to an arbitrary JSON value. + * + * You should usually call [Builder.endDate] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun endDate(endDate: JsonField) = apply { this.endDate = endDate } /** The legal first name of the individual. */ fun firstName(firstName: String?) = firstName(JsonField.ofNullable(firstName)) - /** The legal first name of the individual. */ - fun firstName(firstName: Optional) = firstName(firstName.orElse(null)) + /** Alias for calling [Builder.firstName] with `firstName.orElse(null)`. */ + fun firstName(firstName: Optional) = firstName(firstName.getOrNull()) - /** The legal first name of the individual. */ + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun firstName(firstName: JsonField) = apply { this.firstName = firstName } /** @@ -403,17 +601,14 @@ private constructor( */ fun income(income: Income?) = income(JsonField.ofNullable(income)) - /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. - */ - fun income(income: Optional) = income(income.orElse(null)) + /** Alias for calling [Builder.income] with `income.orElse(null)`. */ + fun income(income: Optional) = income(income.getOrNull()) /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. + * Sets [Builder.income] to an arbitrary JSON value. + * + * You should usually call [Builder.income] with a well-typed [Income] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun income(income: JsonField) = apply { this.income = income } @@ -421,104 +616,167 @@ private constructor( fun incomeHistory(incomeHistory: List?) = incomeHistory(JsonField.ofNullable(incomeHistory)) - /** The array of income history. */ + /** Alias for calling [Builder.incomeHistory] with `incomeHistory.orElse(null)`. */ fun incomeHistory(incomeHistory: Optional>) = - incomeHistory(incomeHistory.orElse(null)) + incomeHistory(incomeHistory.getOrNull()) - /** The array of income history. */ + /** + * Sets [Builder.incomeHistory] to an arbitrary JSON value. + * + * You should usually call [Builder.incomeHistory] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun incomeHistory(incomeHistory: JsonField>) = apply { this.incomeHistory = incomeHistory.map { it.toMutableList() } } - /** The array of income history. */ + /** + * Adds a single [Income] to [Builder.incomeHistory]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addIncomeHistory(incomeHistory: Income) = apply { this.incomeHistory = - (this.incomeHistory ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(incomeHistory) + (this.incomeHistory ?: JsonField.of(mutableListOf())).also { + checkKnown("incomeHistory", it).add(incomeHistory) } } /** `true` if the individual an an active employee or contractor at the company. */ fun isActive(isActive: Boolean?) = isActive(JsonField.ofNullable(isActive)) - /** `true` if the individual an an active employee or contractor at the company. */ + /** + * Alias for [Builder.isActive]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun isActive(isActive: Boolean) = isActive(isActive as Boolean?) - /** `true` if the individual an an active employee or contractor at the company. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun isActive(isActive: Optional) = isActive(isActive.orElse(null) as Boolean?) + /** Alias for calling [Builder.isActive] with `isActive.orElse(null)`. */ + fun isActive(isActive: Optional) = isActive(isActive.getOrNull()) - /** `true` if the individual an an active employee or contractor at the company. */ + /** + * Sets [Builder.isActive] to an arbitrary JSON value. + * + * You should usually call [Builder.isActive] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun isActive(isActive: JsonField) = apply { this.isActive = isActive } /** The legal last name of the individual. */ fun lastName(lastName: String?) = lastName(JsonField.ofNullable(lastName)) - /** The legal last name of the individual. */ - fun lastName(lastName: Optional) = lastName(lastName.orElse(null)) + /** Alias for calling [Builder.lastName] with `lastName.orElse(null)`. */ + fun lastName(lastName: Optional) = lastName(lastName.getOrNull()) - /** The legal last name of the individual. */ + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun lastName(lastName: JsonField) = apply { this.lastName = lastName } fun latestRehireDate(latestRehireDate: String?) = latestRehireDate(JsonField.ofNullable(latestRehireDate)) + /** Alias for calling [Builder.latestRehireDate] with `latestRehireDate.orElse(null)`. */ fun latestRehireDate(latestRehireDate: Optional) = - latestRehireDate(latestRehireDate.orElse(null)) + latestRehireDate(latestRehireDate.getOrNull()) + /** + * Sets [Builder.latestRehireDate] to an arbitrary JSON value. + * + * You should usually call [Builder.latestRehireDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun latestRehireDate(latestRehireDate: JsonField) = apply { this.latestRehireDate = latestRehireDate } fun location(location: Location?) = location(JsonField.ofNullable(location)) - fun location(location: Optional) = location(location.orElse(null)) + /** Alias for calling [Builder.location] with `location.orElse(null)`. */ + fun location(location: Optional) = location(location.getOrNull()) + /** + * Sets [Builder.location] to an arbitrary JSON value. + * + * You should usually call [Builder.location] with a well-typed [Location] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun location(location: JsonField) = apply { this.location = location } /** The manager object representing the manager of the individual within the org. */ fun manager(manager: Manager?) = manager(JsonField.ofNullable(manager)) - /** The manager object representing the manager of the individual within the org. */ - fun manager(manager: Optional) = manager(manager.orElse(null)) + /** Alias for calling [Builder.manager] with `manager.orElse(null)`. */ + fun manager(manager: Optional) = manager(manager.getOrNull()) - /** The manager object representing the manager of the individual within the org. */ + /** + * Sets [Builder.manager] to an arbitrary JSON value. + * + * You should usually call [Builder.manager] with a well-typed [Manager] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun manager(manager: JsonField) = apply { this.manager = manager } /** The legal middle name of the individual. */ fun middleName(middleName: String?) = middleName(JsonField.ofNullable(middleName)) - /** The legal middle name of the individual. */ - fun middleName(middleName: Optional) = middleName(middleName.orElse(null)) + /** Alias for calling [Builder.middleName] with `middleName.orElse(null)`. */ + fun middleName(middleName: Optional) = middleName(middleName.getOrNull()) - /** The legal middle name of the individual. */ + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun middleName(middleName: JsonField) = apply { this.middleName = middleName } /** The source system's unique employment identifier for this individual */ fun sourceId(sourceId: String) = sourceId(JsonField.of(sourceId)) - /** The source system's unique employment identifier for this individual */ + /** + * Sets [Builder.sourceId] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun sourceId(sourceId: JsonField) = apply { this.sourceId = sourceId } fun startDate(startDate: String?) = startDate(JsonField.ofNullable(startDate)) - fun startDate(startDate: Optional) = startDate(startDate.orElse(null)) + /** Alias for calling [Builder.startDate] with `startDate.orElse(null)`. */ + fun startDate(startDate: Optional) = startDate(startDate.getOrNull()) + /** + * Sets [Builder.startDate] to an arbitrary JSON value. + * + * You should usually call [Builder.startDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun startDate(startDate: JsonField) = apply { this.startDate = startDate } /** The current title of the individual. */ fun title(title: String?) = title(JsonField.ofNullable(title)) - /** The current title of the individual. */ - fun title(title: Optional) = title(title.orElse(null)) + /** Alias for calling [Builder.title] with `title.orElse(null)`. */ + fun title(title: Optional) = title(title.getOrNull()) - /** The current title of the individual. */ + /** + * Sets [Builder.title] to an arbitrary JSON value. + * + * You should usually call [Builder.title] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun title(title: JsonField) = apply { this.title = title } fun additionalProperties(additionalProperties: Map) = apply { @@ -540,6 +798,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [EmploymentUpdateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): EmploymentUpdateResponse = EmploymentUpdateResponse( id, @@ -561,47 +824,117 @@ private constructor( sourceId, startDate, title, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): EmploymentUpdateResponse = apply { + if (validated) { + return@apply + } + + id() + classCode() + customFields().ifPresent { it.forEach { it.validate() } } + department().ifPresent { it.validate() } + employment().ifPresent { it.validate() } + employmentStatus().ifPresent { it.validate() } + endDate() + firstName() + income().ifPresent { it.validate() } + incomeHistory().ifPresent { it.forEach { it?.validate() } } + isActive() + lastName() + latestRehireDate() + location().ifPresent { it.validate() } + manager().ifPresent { it.validate() } + middleName() + sourceId() + startDate() + title() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (classCode.asKnown().isPresent) 1 else 0) + + (customFields.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (department.asKnown().getOrNull()?.validity() ?: 0) + + (employment.asKnown().getOrNull()?.validity() ?: 0) + + (employmentStatus.asKnown().getOrNull()?.validity() ?: 0) + + (if (endDate.asKnown().isPresent) 1 else 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (income.asKnown().getOrNull()?.validity() ?: 0) + + (incomeHistory.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (isActive.asKnown().isPresent) 1 else 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (if (latestRehireDate.asKnown().isPresent) 1 else 0) + + (location.asKnown().getOrNull()?.validity() ?: 0) + + (manager.asKnown().getOrNull()?.validity() ?: 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + + (if (sourceId.asKnown().isPresent) 1 else 0) + + (if (startDate.asKnown().isPresent) 1 else 0) + + (if (title.asKnown().isPresent) 1 else 0) + class CustomField - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("value") @ExcludeMissing private val value: JsonValue = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val value: JsonValue, + private val additionalProperties: MutableMap, ) { - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonValue = JsonMissing.of(), + ) : this(name, value, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") @JsonProperty("value") @ExcludeMissing fun _value(): JsonValue = value + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): CustomField = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [CustomField]. */ @JvmStatic fun builder() = Builder() } @@ -621,8 +954,16 @@ private constructor( fun name(name: String?) = name(JsonField.ofNullable(name)) - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } fun value(value: JsonValue) = apply { this.value = value } @@ -646,9 +987,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): CustomField = CustomField(name, value, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [CustomField]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomField = CustomField(name, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CustomField = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -668,42 +1041,47 @@ private constructor( } /** The department object. */ - @NoAutoDetect class Department - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - /** The name of the department associated with the individual. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) + + /** + * The name of the department associated with the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** The name of the department associated with the individual. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Department = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Department]. */ @JvmStatic fun builder() = Builder() } @@ -722,10 +1100,16 @@ private constructor( /** The name of the department associated with the individual. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The name of the department associated with the individual. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The name of the department associated with the individual. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = apply { @@ -747,9 +1131,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Department = Department(name, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Department]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Department = Department(name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Department = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -769,56 +1185,65 @@ private constructor( } /** The employment object. */ - @NoAutoDetect class Employment - @JsonCreator private constructor( - @JsonProperty("subtype") - @ExcludeMissing - private val subtype: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val subtype: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("subtype") @ExcludeMissing subtype: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(subtype, type, mutableMapOf()) + /** * The secondary employment type of the individual. Options: `full_time`, `part_time`, * `intern`, `temp`, `seasonal` and `individual_contractor`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun subtype(): Optional = Optional.ofNullable(subtype.getNullable("subtype")) + fun subtype(): Optional = subtype.getOptional("subtype") - /** The main employment type of the individual. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The main employment type of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") /** - * The secondary employment type of the individual. Options: `full_time`, `part_time`, - * `intern`, `temp`, `seasonal` and `individual_contractor`. + * Returns the raw JSON value of [subtype]. + * + * Unlike [subtype], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype - /** The main employment type of the individual. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Employment = apply { - if (validated) { - return@apply - } - - subtype() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Employment]. */ @JvmStatic fun builder() = Builder() } @@ -842,25 +1267,31 @@ private constructor( */ fun subtype(subtype: Subtype?) = subtype(JsonField.ofNullable(subtype)) - /** - * The secondary employment type of the individual. Options: `full_time`, `part_time`, - * `intern`, `temp`, `seasonal` and `individual_contractor`. - */ - fun subtype(subtype: Optional) = subtype(subtype.orElse(null)) + /** Alias for calling [Builder.subtype] with `subtype.orElse(null)`. */ + fun subtype(subtype: Optional) = subtype(subtype.getOrNull()) /** - * The secondary employment type of the individual. Options: `full_time`, `part_time`, - * `intern`, `temp`, `seasonal` and `individual_contractor`. + * Sets [Builder.subtype] to an arbitrary JSON value. + * + * You should usually call [Builder.subtype] with a well-typed [Subtype] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun subtype(subtype: JsonField) = apply { this.subtype = subtype } /** The main employment type of the individual. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** The main employment type of the individual. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** The main employment type of the individual. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -882,9 +1313,45 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Employment = Employment(subtype, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Employment]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Employment = Employment(subtype, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Employment = apply { + if (validated) { + return@apply + } + + subtype().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (subtype.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + /** * The secondary employment type of the individual. Options: `full_time`, `part_time`, * `intern`, `temp`, `seasonal` and `individual_contractor`. @@ -1003,6 +1470,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Subtype = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1104,6 +1598,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1254,6 +1775,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EmploymentStatus = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1268,40 +1816,47 @@ private constructor( } /** The manager object representing the manager of the individual within the org. */ - @NoAutoDetect class Manager - @JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val additionalProperties: MutableMap, ) { - /** A stable Finch `id` (UUID v4) for an individual in the company. */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of() + ) : this(id, mutableMapOf()) - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * A stable Finch `id` (UUID v4) for an individual in the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Manager = apply { - if (validated) { - return@apply - } - - id() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Manager]. */ @JvmStatic fun builder() = Builder() } @@ -1320,7 +1875,13 @@ private constructor( /** A stable Finch `id` (UUID v4) for an individual in the company. */ fun id(id: String) = id(JsonField.of(id)) - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun id(id: JsonField) = apply { this.id = id } fun additionalProperties(additionalProperties: Map) = apply { @@ -1342,9 +1903,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Manager = Manager(id, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Manager]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Manager = Manager(id, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Manager = apply { + if (validated) { + return@apply + } + + id() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (id.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EnrolledIndividual.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EnrolledIndividual.kt index 8f31d858..f2a7666c 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EnrolledIndividual.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/EnrolledIndividual.kt @@ -11,64 +11,87 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class EnrolledIndividual -@JsonCreator private constructor( - @JsonProperty("body") @ExcludeMissing private val body: JsonField = JsonMissing.of(), - @JsonProperty("code") @ExcludeMissing private val code: JsonField = JsonMissing.of(), - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val body: JsonField, + private val code: JsonField, + private val individualId: JsonField, + private val additionalProperties: MutableMap, ) { - fun body(): Optional = Optional.ofNullable(body.getNullable("body")) - - /** HTTP status code. Either 201 or 200 */ - fun code(): Optional = Optional.ofNullable(code.getNullable("code")) - - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) - + @JsonCreator + private constructor( + @JsonProperty("body") @ExcludeMissing body: JsonField = JsonMissing.of(), + @JsonProperty("code") @ExcludeMissing code: JsonField = JsonMissing.of(), + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of(), + ) : this(body, code, individualId, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun body(): Optional = body.getOptional("body") + + /** + * HTTP status code. Either 201 or 200 + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun code(): Optional = code.getOptional("code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") + + /** + * Returns the raw JSON value of [body]. + * + * Unlike [body], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("body") @ExcludeMissing fun _body(): JsonField = body - /** HTTP status code. Either 201 or 200 */ + /** + * Returns the raw JSON value of [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): EnrolledIndividual = apply { - if (validated) { - return@apply - } - - body().ifPresent { it.validate() } - code() - individualId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [EnrolledIndividual]. */ @JvmStatic fun builder() = Builder() } @@ -90,16 +113,34 @@ private constructor( fun body(body: Body) = body(JsonField.of(body)) + /** + * Sets [Builder.body] to an arbitrary JSON value. + * + * You should usually call [Builder.body] with a well-typed [Body] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun body(body: JsonField) = apply { this.body = body } /** HTTP status code. Either 201 or 200 */ fun code(code: Code) = code(JsonField.of(code)) - /** HTTP status code. Either 201 or 200 */ + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [Code] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun code(code: JsonField) = apply { this.code = code } fun individualId(individualId: String) = individualId(JsonField.of(individualId)) + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -123,66 +164,124 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [EnrolledIndividual]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): EnrolledIndividual = - EnrolledIndividual(body, code, individualId, additionalProperties.toImmutable()) + EnrolledIndividual(body, code, individualId, additionalProperties.toMutableMap()) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): EnrolledIndividual = apply { + if (validated) { + return@apply + } + + body().ifPresent { it.validate() } + code().ifPresent { it.validate() } + individualId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (body.asKnown().getOrNull()?.validity() ?: 0) + + (code.asKnown().getOrNull()?.validity() ?: 0) + + (if (individualId.asKnown().isPresent) 1 else 0) + class Body - @JsonCreator private constructor( - @JsonProperty("finch_code") - @ExcludeMissing - private val finchCode: JsonField = JsonMissing.of(), - @JsonProperty("message") - @ExcludeMissing - private val message: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val finchCode: JsonField, + private val message: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - /** A descriptive identifier for the response */ - fun finchCode(): Optional = Optional.ofNullable(finchCode.getNullable("finch_code")) + @JsonCreator + private constructor( + @JsonProperty("finch_code") + @ExcludeMissing + finchCode: JsonField = JsonMissing.of(), + @JsonProperty("message") @ExcludeMissing message: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(finchCode, message, name, mutableMapOf()) + + /** + * A descriptive identifier for the response. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun finchCode(): Optional = finchCode.getOptional("finch_code") - /** Short description in English that provides more information about the response. */ - fun message(): Optional = Optional.ofNullable(message.getNullable("message")) + /** + * Short description in English that provides more information about the response. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun message(): Optional = message.getOptional("message") - /** Identifier indicating whether the benefit was newly enrolled or updated. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + /** + * Identifier indicating whether the benefit was newly enrolled or updated. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** A descriptive identifier for the response */ + /** + * Returns the raw JSON value of [finchCode]. + * + * Unlike [finchCode], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("finch_code") @ExcludeMissing fun _finchCode(): JsonField = finchCode - /** Short description in English that provides more information about the response. */ + /** + * Returns the raw JSON value of [message]. + * + * Unlike [message], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message - /** Identifier indicating whether the benefit was newly enrolled or updated. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - finchCode() - message() - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Body]. */ @JvmStatic fun builder() = Builder() } @@ -202,31 +301,49 @@ private constructor( additionalProperties = body.additionalProperties.toMutableMap() } - /** A descriptive identifier for the response */ + /** A descriptive identifier for the response. */ fun finchCode(finchCode: String?) = finchCode(JsonField.ofNullable(finchCode)) - /** A descriptive identifier for the response */ - fun finchCode(finchCode: Optional) = finchCode(finchCode.orElse(null)) + /** Alias for calling [Builder.finchCode] with `finchCode.orElse(null)`. */ + fun finchCode(finchCode: Optional) = finchCode(finchCode.getOrNull()) - /** A descriptive identifier for the response */ + /** + * Sets [Builder.finchCode] to an arbitrary JSON value. + * + * You should usually call [Builder.finchCode] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun finchCode(finchCode: JsonField) = apply { this.finchCode = finchCode } /** Short description in English that provides more information about the response. */ fun message(message: String?) = message(JsonField.ofNullable(message)) - /** Short description in English that provides more information about the response. */ - fun message(message: Optional) = message(message.orElse(null)) + /** Alias for calling [Builder.message] with `message.orElse(null)`. */ + fun message(message: Optional) = message(message.getOrNull()) - /** Short description in English that provides more information about the response. */ + /** + * Sets [Builder.message] to an arbitrary JSON value. + * + * You should usually call [Builder.message] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun message(message: JsonField) = apply { this.message = message } /** Identifier indicating whether the benefit was newly enrolled or updated. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** Identifier indicating whether the benefit was newly enrolled or updated. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** Identifier indicating whether the benefit was newly enrolled or updated. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = apply { @@ -248,9 +365,47 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Body = Body(finchCode, message, name, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = Body(finchCode, message, name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + finchCode() + message() + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (finchCode.asKnown().isPresent) 1 else 0) + + (if (message.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -365,6 +520,33 @@ private constructor( if (it.toDouble() % 1 == 0.0) it.toLong() else null } ?: throw FinchInvalidDataException("Value is not a Long") + private var validated: Boolean = false + + fun validate(): Code = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitCreateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitCreateParams.kt index 868e087a..72a4557e 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitCreateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitCreateParams.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** * Creates a new company-wide deduction or contribution. Please use the `/providers` endpoint to @@ -33,23 +33,47 @@ private constructor( /** * Name of the benefit as it appears in the provider and pay statements. Recommend limiting this * to <30 characters due to limitations in specific providers (e.g. Justworks). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ fun description(): Optional = body.description() + /** + * The frequency of the benefit deduction/contribution. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun frequency(): Optional = body.frequency() - /** Type of benefit. */ + /** + * Type of benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun type(): Optional = body.type() /** - * Name of the benefit as it appears in the provider and pay statements. Recommend limiting this - * to <30 characters due to limitations in specific providers (e.g. Justworks). + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. */ fun _description(): JsonField = body._description() + /** + * Returns the raw JSON value of [frequency]. + * + * Unlike [frequency], this method doesn't throw if the JSON field has an unexpected type. + */ fun _frequency(): JsonField = body._frequency() - /** Type of benefit. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ fun _type(): JsonField = body._type() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -58,182 +82,17 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("frequency") - @ExcludeMissing - private val frequency: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * Name of the benefit as it appears in the provider and pay statements. Recommend limiting - * this to <30 characters due to limitations in specific providers (e.g. Justworks). - */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - fun frequency(): Optional = - Optional.ofNullable(frequency.getNullable("frequency")) - - /** Type of benefit. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** - * Name of the benefit as it appears in the provider and pay statements. Recommend limiting - * this to <30 characters due to limitations in specific providers (e.g. Justworks). - */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description - - @JsonProperty("frequency") - @ExcludeMissing - fun _frequency(): JsonField = frequency - - /** Type of benefit. */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - description() - frequency() - type() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var description: JsonField = JsonMissing.of() - private var frequency: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - description = body.description - frequency = body.frequency - type = body.type - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** - * Name of the benefit as it appears in the provider and pay statements. Recommend - * limiting this to <30 characters due to limitations in specific providers (e.g. - * Justworks). - */ - fun description(description: String) = description(JsonField.of(description)) - - /** - * Name of the benefit as it appears in the provider and pay statements. Recommend - * limiting this to <30 characters due to limitations in specific providers (e.g. - * Justworks). - */ - fun description(description: JsonField) = apply { - this.description = description - } - - fun frequency(frequency: BenefitFrequency?) = frequency(JsonField.ofNullable(frequency)) - - fun frequency(frequency: Optional) = frequency(frequency.orElse(null)) - - fun frequency(frequency: JsonField) = apply { - this.frequency = frequency - } - - /** Type of benefit. */ - fun type(type: BenefitType?) = type(JsonField.ofNullable(type)) - - /** Type of benefit. */ - fun type(type: Optional) = type(type.orElse(null)) - - /** Type of benefit. */ - fun type(type: JsonField) = apply { this.type = type } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = - Body(description, frequency, type, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && description == other.description && frequency == other.frequency && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(description, frequency, type, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{description=$description, frequency=$frequency, type=$type, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): HrisBenefitCreateParams = builder().build() + /** Returns a mutable builder for constructing an instance of [HrisBenefitCreateParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisBenefitCreateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -247,6 +106,17 @@ private constructor( additionalQueryParams = hrisBenefitCreateParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [description] + * - [frequency] + * - [type] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** * Name of the benefit as it appears in the provider and pay statements. Recommend limiting * this to <30 characters due to limitations in specific providers (e.g. Justworks). @@ -254,24 +124,42 @@ private constructor( fun description(description: String) = apply { body.description(description) } /** - * Name of the benefit as it appears in the provider and pay statements. Recommend limiting - * this to <30 characters due to limitations in specific providers (e.g. Justworks). + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ fun description(description: JsonField) = apply { body.description(description) } + /** The frequency of the benefit deduction/contribution. */ fun frequency(frequency: BenefitFrequency?) = apply { body.frequency(frequency) } - fun frequency(frequency: Optional) = frequency(frequency.orElse(null)) + /** Alias for calling [Builder.frequency] with `frequency.orElse(null)`. */ + fun frequency(frequency: Optional) = frequency(frequency.getOrNull()) + /** + * Sets [Builder.frequency] to an arbitrary JSON value. + * + * You should usually call [Builder.frequency] with a well-typed [BenefitFrequency] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun frequency(frequency: JsonField) = apply { body.frequency(frequency) } /** Type of benefit. */ fun type(type: BenefitType?) = apply { body.type(type) } - /** Type of benefit. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** Type of benefit. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [BenefitType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { body.type(type) } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { @@ -391,6 +279,11 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisBenefitCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): HrisBenefitCreateParams = HrisBenefitCreateParams( body.build(), @@ -399,6 +292,244 @@ private constructor( ) } + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val description: JsonField, + private val frequency: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("frequency") + @ExcludeMissing + frequency: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(description, frequency, type, mutableMapOf()) + + /** + * Name of the benefit as it appears in the provider and pay statements. Recommend limiting + * this to <30 characters due to limitations in specific providers (e.g. Justworks). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * The frequency of the benefit deduction/contribution. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun frequency(): Optional = frequency.getOptional("frequency") + + /** + * Type of benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + /** + * Returns the raw JSON value of [frequency]. + * + * Unlike [frequency], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("frequency") + @ExcludeMissing + fun _frequency(): JsonField = frequency + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var description: JsonField = JsonMissing.of() + private var frequency: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + description = body.description + frequency = body.frequency + type = body.type + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** + * Name of the benefit as it appears in the provider and pay statements. Recommend + * limiting this to <30 characters due to limitations in specific providers (e.g. + * Justworks). + */ + fun description(description: String) = description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + /** The frequency of the benefit deduction/contribution. */ + fun frequency(frequency: BenefitFrequency?) = frequency(JsonField.ofNullable(frequency)) + + /** Alias for calling [Builder.frequency] with `frequency.orElse(null)`. */ + fun frequency(frequency: Optional) = frequency(frequency.getOrNull()) + + /** + * Sets [Builder.frequency] to an arbitrary JSON value. + * + * You should usually call [Builder.frequency] with a well-typed [BenefitFrequency] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun frequency(frequency: JsonField) = apply { + this.frequency = frequency + } + + /** Type of benefit. */ + fun type(type: BenefitType?) = type(JsonField.ofNullable(type)) + + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [BenefitType] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body(description, frequency, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + description() + frequency().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (description.asKnown().isPresent) 1 else 0) + + (frequency.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && description == other.description && frequency == other.frequency && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(description, frequency, type, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{description=$description, frequency=$frequency, type=$type, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualEnrolledIdsParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualEnrolledIdsParams.kt index 4e98d670..ed8fb88a 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualEnrolledIdsParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualEnrolledIdsParams.kt @@ -2,7 +2,6 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers @@ -23,26 +22,23 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> benefitId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisBenefitIndividualEnrolledIdsParams]. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisBenefitIndividualEnrolledIdsParams]. */ - @NoAutoDetect class Builder internal constructor() { private var benefitId: String? = null @@ -159,6 +155,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisBenefitIndividualEnrolledIdsParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): HrisBenefitIndividualEnrolledIdsParams = HrisBenefitIndividualEnrolledIdsParams( checkRequired("benefitId", benefitId), @@ -167,6 +175,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> benefitId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsPage.kt index d00f2f3a..6ca15012 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsPage.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsPage.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.blocking.hris.benefits.IndividualService +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull /** Get enrollment information for the given individuals. */ class HrisBenefitIndividualRetrieveManyBenefitsPage @@ -68,24 +68,30 @@ private constructor( ) = HrisBenefitIndividualRetrieveManyBenefitsPage(individualsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -98,6 +104,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -115,6 +129,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisBenefitIndividualRetrieveManyBenefitsPage]. + */ @JvmStatic fun builder() = Builder() } @@ -137,7 +155,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } @@ -151,7 +174,7 @@ private constructor( while (index < page.items().size) { yield(page.items()[index++]) } - page = page.getNextPage().orElse(null) ?: break + page = page.getNextPage().getOrNull() ?: break index = 0 } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsPageAsync.kt index 6c87b64f..1ff8bb43 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsPageAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsPageAsync.kt @@ -10,15 +10,15 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.async.hris.benefits.IndividualServiceAsync +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull /** Get enrollment information for the given individuals. */ class HrisBenefitIndividualRetrieveManyBenefitsPageAsync @@ -72,24 +72,30 @@ private constructor( ) = HrisBenefitIndividualRetrieveManyBenefitsPageAsync(individualsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -102,6 +108,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -119,6 +133,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisBenefitIndividualRetrieveManyBenefitsPageAsync]. + */ @JvmStatic fun builder() = Builder() } @@ -141,7 +159,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsParams.kt index bb05a6ef..dd2e70a8 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsParams.kt @@ -2,13 +2,13 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Get enrollment information for the given individuals. */ class HrisBenefitIndividualRetrieveManyBenefitsParams @@ -31,31 +31,23 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.individualIds?.let { queryParams.put("individual_ids", listOf(it.toString())) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> benefitId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisBenefitIndividualRetrieveManyBenefitsParams]. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisBenefitIndividualRetrieveManyBenefitsParams]. */ - @NoAutoDetect class Builder internal constructor() { private var benefitId: String? = null @@ -84,12 +76,9 @@ private constructor( */ fun individualIds(individualIds: String?) = apply { this.individualIds = individualIds } - /** - * comma-delimited list of stable Finch uuids for each individual. If empty, defaults to all - * individuals - */ + /** Alias for calling [Builder.individualIds] with `individualIds.orElse(null)`. */ fun individualIds(individualIds: Optional) = - individualIds(individualIds.orElse(null)) + individualIds(individualIds.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -189,6 +178,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisBenefitIndividualRetrieveManyBenefitsParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): HrisBenefitIndividualRetrieveManyBenefitsParams = HrisBenefitIndividualRetrieveManyBenefitsParams( checkRequired("benefitId", benefitId), @@ -198,6 +199,22 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> benefitId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + individualIds?.let { put("individual_ids", it) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyPage.kt index fbd19014..2b7b92b4 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyPage.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyPage.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.blocking.hris.benefits.IndividualService +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull /** Unenroll individuals from a deduction or contribution */ class HrisBenefitIndividualUnenrollManyPage @@ -68,24 +68,30 @@ private constructor( ) = HrisBenefitIndividualUnenrollManyPage(individualsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -98,6 +104,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -115,6 +129,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisBenefitIndividualUnenrollManyPage]. + */ @JvmStatic fun builder() = Builder() } @@ -137,7 +155,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } @@ -151,7 +174,7 @@ private constructor( while (index < page.items().size) { yield(page.items()[index++]) } - page = page.getNextPage().orElse(null) ?: break + page = page.getNextPage().getOrNull() ?: break index = 0 } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyPageAsync.kt index 2540f64e..e569d5ee 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyPageAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyPageAsync.kt @@ -10,15 +10,15 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.async.hris.benefits.IndividualServiceAsync +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull /** Unenroll individuals from a deduction or contribution */ class HrisBenefitIndividualUnenrollManyPageAsync @@ -71,24 +71,30 @@ private constructor( ) = HrisBenefitIndividualUnenrollManyPageAsync(individualsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -101,6 +107,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -118,6 +132,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisBenefitIndividualUnenrollManyPageAsync]. + */ @JvmStatic fun builder() = Builder() } @@ -140,7 +158,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyParams.kt index 9994d336..da3f66cd 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyParams.kt @@ -10,15 +10,17 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Unenroll individuals from a deduction or contribution */ class HrisBenefitIndividualUnenrollManyParams @@ -31,10 +33,19 @@ private constructor( fun benefitId(): String = benefitId - /** Array of individual_ids to unenroll. */ + /** + * Array of individual_ids to unenroll. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun individualIds(): Optional> = body.individualIds() - /** Array of individual_ids to unenroll. */ + /** + * Returns the raw JSON value of [individualIds]. + * + * Unlike [individualIds], this method doesn't throw if the JSON field has an unexpected type. + */ fun _individualIds(): JsonField> = body._individualIds() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -43,149 +54,23 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> benefitId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("individual_ids") - @ExcludeMissing - private val individualIds: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** Array of individual_ids to unenroll. */ - fun individualIds(): Optional> = - Optional.ofNullable(individualIds.getNullable("individual_ids")) - - /** Array of individual_ids to unenroll. */ - @JsonProperty("individual_ids") - @ExcludeMissing - fun _individualIds(): JsonField> = individualIds - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - individualIds() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var individualIds: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - individualIds = body.individualIds.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Array of individual_ids to unenroll. */ - fun individualIds(individualIds: List) = - individualIds(JsonField.of(individualIds)) - - /** Array of individual_ids to unenroll. */ - fun individualIds(individualIds: JsonField>) = apply { - this.individualIds = individualIds.map { it.toMutableList() } - } - - /** Array of individual_ids to unenroll. */ - fun addIndividualId(individualId: String) = apply { - individualIds = - (individualIds ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(individualId) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = - Body( - (individualIds ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && individualIds == other.individualIds && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(individualIds, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{individualIds=$individualIds, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisBenefitIndividualUnenrollManyParams]. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisBenefitIndividualUnenrollManyParams]. */ - @NoAutoDetect class Builder internal constructor() { private var benefitId: String? = null @@ -207,15 +92,34 @@ private constructor( fun benefitId(benefitId: String) = apply { this.benefitId = benefitId } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [individualIds] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** Array of individual_ids to unenroll. */ fun individualIds(individualIds: List) = apply { body.individualIds(individualIds) } - /** Array of individual_ids to unenroll. */ + /** + * Sets [Builder.individualIds] to an arbitrary JSON value. + * + * You should usually call [Builder.individualIds] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun individualIds(individualIds: JsonField>) = apply { body.individualIds(individualIds) } - /** Array of individual_ids to unenroll. */ + /** + * Adds a single [String] to [individualIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addIndividualId(individualId: String) = apply { body.addIndividualId(individualId) } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { @@ -335,6 +239,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisBenefitIndividualUnenrollManyParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): HrisBenefitIndividualUnenrollManyParams = HrisBenefitIndividualUnenrollManyParams( checkRequired("benefitId", benefitId), @@ -344,6 +260,183 @@ private constructor( ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> benefitId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val individualIds: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("individual_ids") + @ExcludeMissing + individualIds: JsonField> = JsonMissing.of() + ) : this(individualIds, mutableMapOf()) + + /** + * Array of individual_ids to unenroll. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualIds(): Optional> = individualIds.getOptional("individual_ids") + + /** + * Returns the raw JSON value of [individualIds]. + * + * Unlike [individualIds], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("individual_ids") + @ExcludeMissing + fun _individualIds(): JsonField> = individualIds + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var individualIds: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + individualIds = body.individualIds.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Array of individual_ids to unenroll. */ + fun individualIds(individualIds: List) = + individualIds(JsonField.of(individualIds)) + + /** + * Sets [Builder.individualIds] to an arbitrary JSON value. + * + * You should usually call [Builder.individualIds] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun individualIds(individualIds: JsonField>) = apply { + this.individualIds = individualIds.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [individualIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addIndividualId(individualId: String) = apply { + individualIds = + (individualIds ?: JsonField.of(mutableListOf())).also { + checkKnown("individualIds", it).add(individualId) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body( + (individualIds ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + individualIds() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (individualIds.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && individualIds == other.individualIds && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(individualIds, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{individualIds=$individualIds, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListPage.kt index b2a4c5d6..55732adf 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListPage.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListPage.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.blocking.hris.BenefitService +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull /** List all company-wide deductions and contributions. */ class HrisBenefitListPage @@ -65,24 +65,30 @@ private constructor( HrisBenefitListPage(benefitsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -95,6 +101,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -112,6 +126,7 @@ private constructor( companion object { + /** Returns a mutable builder for constructing an instance of [HrisBenefitListPage]. */ @JvmStatic fun builder() = Builder() } @@ -134,7 +149,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } @@ -147,7 +167,7 @@ private constructor( while (index < page.items().size) { yield(page.items()[index++]) } - page = page.getNextPage().orElse(null) ?: break + page = page.getNextPage().getOrNull() ?: break index = 0 } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListPageAsync.kt index fcd50f1f..1dd66c6b 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListPageAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListPageAsync.kt @@ -10,15 +10,15 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.async.hris.BenefitServiceAsync +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull /** List all company-wide deductions and contributions. */ class HrisBenefitListPageAsync @@ -71,24 +71,30 @@ private constructor( ) = HrisBenefitListPageAsync(benefitsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -101,6 +107,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -118,6 +132,9 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of [HrisBenefitListPageAsync]. + */ @JvmStatic fun builder() = Builder() } @@ -140,7 +157,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListParams.kt index 63ae4bf0..daaa4c63 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListParams.kt @@ -2,7 +2,6 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams @@ -19,21 +18,17 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): HrisBenefitListParams = builder().build() + /** Returns a mutable builder for constructing an instance of [HrisBenefitListParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisBenefitListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var additionalHeaders: Headers.Builder = Headers.builder() @@ -143,10 +138,19 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisBenefitListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): HrisBenefitListParams = HrisBenefitListParams(additionalHeaders.build(), additionalQueryParams.build()) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsPage.kt index 5e65cc88..3d15fd51 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsPage.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsPage.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.blocking.hris.BenefitService +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull /** Get deductions metadata */ class HrisBenefitListSupportedBenefitsPage @@ -68,24 +68,30 @@ private constructor( ) = HrisBenefitListSupportedBenefitsPage(benefitsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -98,6 +104,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -115,6 +129,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisBenefitListSupportedBenefitsPage]. + */ @JvmStatic fun builder() = Builder() } @@ -137,7 +155,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } @@ -151,7 +174,7 @@ private constructor( while (index < page.items().size) { yield(page.items()[index++]) } - page = page.getNextPage().orElse(null) ?: break + page = page.getNextPage().getOrNull() ?: break index = 0 } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsPageAsync.kt index e21eb7f7..b839cb7a 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsPageAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsPageAsync.kt @@ -10,15 +10,15 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.async.hris.BenefitServiceAsync +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull /** Get deductions metadata */ class HrisBenefitListSupportedBenefitsPageAsync @@ -71,24 +71,30 @@ private constructor( ) = HrisBenefitListSupportedBenefitsPageAsync(benefitsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -101,6 +107,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -118,6 +132,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisBenefitListSupportedBenefitsPageAsync]. + */ @JvmStatic fun builder() = Builder() } @@ -140,7 +158,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsParams.kt index c783f66b..df408510 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsParams.kt @@ -2,7 +2,6 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams @@ -19,21 +18,20 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): HrisBenefitListSupportedBenefitsParams = builder().build() + /** + * Returns a mutable builder for constructing an instance of + * [HrisBenefitListSupportedBenefitsParams]. + */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisBenefitListSupportedBenefitsParams]. */ - @NoAutoDetect class Builder internal constructor() { private var additionalHeaders: Headers.Builder = Headers.builder() @@ -146,6 +144,11 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisBenefitListSupportedBenefitsParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): HrisBenefitListSupportedBenefitsParams = HrisBenefitListSupportedBenefitsParams( additionalHeaders.build(), @@ -153,6 +156,10 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitRetrieveParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitRetrieveParams.kt index 05594957..0167113d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitRetrieveParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitRetrieveParams.kt @@ -2,7 +2,6 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers @@ -23,26 +22,22 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> benefitId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [HrisBenefitRetrieveParams]. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisBenefitRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var benefitId: String? = null @@ -156,6 +151,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisBenefitRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): HrisBenefitRetrieveParams = HrisBenefitRetrieveParams( checkRequired("benefitId", benefitId), @@ -164,6 +171,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> benefitId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitUpdateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitUpdateParams.kt index f3e83adb..91bc5f13 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitUpdateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisBenefitUpdateParams.kt @@ -10,13 +10,12 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional @@ -31,10 +30,19 @@ private constructor( fun benefitId(): String = benefitId - /** Updated name or description. */ + /** + * Updated name or description. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun description(): Optional = body.description() - /** Updated name or description. */ + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ fun _description(): JsonField = body._description() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -43,130 +51,22 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> benefitId - else -> "" - } - } - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** Updated name or description. */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - /** Updated name or description. */ - @JsonProperty("description") - @ExcludeMissing - fun _description(): JsonField = description - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - description() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var description: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - description = body.description - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** Updated name or description. */ - fun description(description: String) = description(JsonField.of(description)) - - /** Updated name or description. */ - fun description(description: JsonField) = apply { - this.description = description - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = Body(description, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && description == other.description && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(description, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{description=$description, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [HrisBenefitUpdateParams]. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisBenefitUpdateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var benefitId: String? = null @@ -184,10 +84,25 @@ private constructor( fun benefitId(benefitId: String) = apply { this.benefitId = benefitId } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [description] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** Updated name or description. */ fun description(description: String) = apply { body.description(description) } - /** Updated name or description. */ + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun description(description: JsonField) = apply { body.description(description) } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { @@ -307,6 +222,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisBenefitUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): HrisBenefitUpdateParams = HrisBenefitUpdateParams( checkRequired("benefitId", benefitId), @@ -316,6 +243,164 @@ private constructor( ) } + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> benefitId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val description: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of() + ) : this(description, mutableMapOf()) + + /** + * Updated name or description. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var description: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + description = body.description + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Updated name or description. */ + fun description(description: String) = description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = Body(description, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + description() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (description.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && description == other.description && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(description, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{description=$description, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemListPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemListPage.kt new file mode 100644 index 00000000..fc858012 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemListPage.kt @@ -0,0 +1,196 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.tryfinch.api.core.ExcludeMissing +import com.tryfinch.api.core.JsonField +import com.tryfinch.api.core.JsonMissing +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.errors.FinchInvalidDataException +import com.tryfinch.api.services.blocking.hris.company.PayStatementItemService +import java.util.Collections +import java.util.Objects +import java.util.Optional +import java.util.stream.Stream +import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull + +/** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Retrieve a list of detailed pay statement items for the access token's + * connection account. + */ +class HrisCompanyPayStatementItemListPage +private constructor( + private val payStatementItemService: PayStatementItemService, + private val params: HrisCompanyPayStatementItemListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun responses(): List = response().responses() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is HrisCompanyPayStatementItemListPage && payStatementItemService == other.payStatementItemService && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(payStatementItemService, params, response) /* spotless:on */ + + override fun toString() = + "HrisCompanyPayStatementItemListPage{payStatementItemService=$payStatementItemService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !responses().isEmpty() + } + + fun getNextPageParams(): Optional { + return Optional.empty() + } + + fun getNextPage(): Optional { + return getNextPageParams().map { payStatementItemService.list(it) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of( + payStatementItemService: PayStatementItemService, + params: HrisCompanyPayStatementItemListParams, + response: Response, + ) = HrisCompanyPayStatementItemListPage(payStatementItemService, params, response) + } + + class Response( + private val responses: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("responses") + responses: JsonField> = JsonMissing.of() + ) : this(responses, mutableMapOf()) + + fun responses(): List = + responses.getOptional("responses").getOrNull() ?: listOf() + + @JsonProperty("responses") + fun _responses(): Optional>> = + Optional.ofNullable(responses) + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + private var validated: Boolean = false + + fun validate(): Response = apply { + if (validated) { + return@apply + } + + responses().map { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Response && responses == other.responses && additionalProperties == other.additionalProperties /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(responses, additionalProperties) /* spotless:on */ + + override fun toString() = + "Response{responses=$responses, additionalProperties=$additionalProperties}" + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [HrisCompanyPayStatementItemListPage]. + */ + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var responses: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.responses = page.responses + this.additionalProperties.putAll(page.additionalProperties) + } + + fun responses(responses: List) = + responses(JsonField.of(responses)) + + fun responses(responses: JsonField>) = apply { + this.responses = responses + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(responses, additionalProperties.toMutableMap()) + } + } + + class AutoPager(private val firstPage: HrisCompanyPayStatementItemListPage) : + Iterable { + + override fun iterator(): Iterator = iterator { + var page = firstPage + var index = 0 + while (true) { + while (index < page.responses().size) { + yield(page.responses()[index++]) + } + page = page.getNextPage().getOrNull() ?: break + index = 0 + } + } + + fun stream(): Stream { + return StreamSupport.stream(spliterator(), false) + } + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemListPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemListPageAsync.kt new file mode 100644 index 00000000..5963daa3 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemListPageAsync.kt @@ -0,0 +1,208 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.tryfinch.api.core.ExcludeMissing +import com.tryfinch.api.core.JsonField +import com.tryfinch.api.core.JsonMissing +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.errors.FinchInvalidDataException +import com.tryfinch.api.services.async.hris.company.PayStatementItemServiceAsync +import java.util.Collections +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull + +/** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Retrieve a list of detailed pay statement items for the access token's + * connection account. + */ +class HrisCompanyPayStatementItemListPageAsync +private constructor( + private val payStatementItemService: PayStatementItemServiceAsync, + private val params: HrisCompanyPayStatementItemListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun responses(): List = response().responses() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is HrisCompanyPayStatementItemListPageAsync && payStatementItemService == other.payStatementItemService && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(payStatementItemService, params, response) /* spotless:on */ + + override fun toString() = + "HrisCompanyPayStatementItemListPageAsync{payStatementItemService=$payStatementItemService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !responses().isEmpty() + } + + fun getNextPageParams(): Optional { + return Optional.empty() + } + + fun getNextPage(): CompletableFuture> { + return getNextPageParams() + .map { payStatementItemService.list(it).thenApply { Optional.of(it) } } + .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of( + payStatementItemService: PayStatementItemServiceAsync, + params: HrisCompanyPayStatementItemListParams, + response: Response, + ) = HrisCompanyPayStatementItemListPageAsync(payStatementItemService, params, response) + } + + class Response( + private val responses: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("responses") + responses: JsonField> = JsonMissing.of() + ) : this(responses, mutableMapOf()) + + fun responses(): List = + responses.getOptional("responses").getOrNull() ?: listOf() + + @JsonProperty("responses") + fun _responses(): Optional>> = + Optional.ofNullable(responses) + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + private var validated: Boolean = false + + fun validate(): Response = apply { + if (validated) { + return@apply + } + + responses().map { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Response && responses == other.responses && additionalProperties == other.additionalProperties /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(responses, additionalProperties) /* spotless:on */ + + override fun toString() = + "Response{responses=$responses, additionalProperties=$additionalProperties}" + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [HrisCompanyPayStatementItemListPageAsync]. + */ + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var responses: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.responses = page.responses + this.additionalProperties.putAll(page.additionalProperties) + } + + fun responses(responses: List) = + responses(JsonField.of(responses)) + + fun responses(responses: JsonField>) = apply { + this.responses = responses + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(responses, additionalProperties.toMutableMap()) + } + } + + class AutoPager(private val firstPage: HrisCompanyPayStatementItemListPageAsync) { + + fun forEach( + action: Predicate, + executor: Executor, + ): CompletableFuture { + fun CompletableFuture>.forEach( + action: (PayStatementItemListResponse) -> Boolean, + executor: Executor, + ): CompletableFuture = + thenComposeAsync( + { page -> + page + .filter { it.responses().all(action) } + .map { it.getNextPage().forEach(action, executor) } + .orElseGet { CompletableFuture.completedFuture(null) } + }, + executor, + ) + return CompletableFuture.completedFuture(Optional.of(firstPage)) + .forEach(action::test, executor) + } + + fun toList(executor: Executor): CompletableFuture> { + val values = mutableListOf() + return forEach(values::add, executor).thenApply { values } + } + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemListParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemListParams.kt new file mode 100644 index 00000000..5c38f85d --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemListParams.kt @@ -0,0 +1,427 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonCreator +import com.tryfinch.api.core.Enum +import com.tryfinch.api.core.JsonField +import com.tryfinch.api.core.Params +import com.tryfinch.api.core.http.Headers +import com.tryfinch.api.core.http.QueryParams +import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.time.LocalDate +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Retrieve a list of detailed pay statement items for the access token's + * connection account. + */ +class HrisCompanyPayStatementItemListParams +private constructor( + private val categories: List?, + private val endDate: LocalDate?, + private val name: String?, + private val startDate: LocalDate?, + private val type: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Comma-delimited list of pay statement item categories to filter on. If empty, defaults to all + * categories. + */ + fun categories(): Optional> = Optional.ofNullable(categories) + + /** + * The end date to retrieve pay statement items by via their last seen pay date in `YYYY-MM-DD` + * format. + */ + fun endDate(): Optional = Optional.ofNullable(endDate) + + /** Case-insensitive partial match search by pay statement item name. */ + fun name(): Optional = Optional.ofNullable(name) + + /** + * The start date to retrieve pay statement items by via their last seen pay date (inclusive) in + * `YYYY-MM-DD` format. + */ + fun startDate(): Optional = Optional.ofNullable(startDate) + + /** String search by pay statement item type. */ + fun type(): Optional = Optional.ofNullable(type) + + fun _additionalHeaders(): Headers = additionalHeaders + + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): HrisCompanyPayStatementItemListParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of + * [HrisCompanyPayStatementItemListParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [HrisCompanyPayStatementItemListParams]. */ + class Builder internal constructor() { + + private var categories: MutableList? = null + private var endDate: LocalDate? = null + private var name: String? = null + private var startDate: LocalDate? = null + private var type: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from( + hrisCompanyPayStatementItemListParams: HrisCompanyPayStatementItemListParams + ) = apply { + categories = hrisCompanyPayStatementItemListParams.categories?.toMutableList() + endDate = hrisCompanyPayStatementItemListParams.endDate + name = hrisCompanyPayStatementItemListParams.name + startDate = hrisCompanyPayStatementItemListParams.startDate + type = hrisCompanyPayStatementItemListParams.type + additionalHeaders = hrisCompanyPayStatementItemListParams.additionalHeaders.toBuilder() + additionalQueryParams = + hrisCompanyPayStatementItemListParams.additionalQueryParams.toBuilder() + } + + /** + * Comma-delimited list of pay statement item categories to filter on. If empty, defaults to + * all categories. + */ + fun categories(categories: List?) = apply { + this.categories = categories?.toMutableList() + } + + /** Alias for calling [Builder.categories] with `categories.orElse(null)`. */ + fun categories(categories: Optional>) = categories(categories.getOrNull()) + + /** + * Adds a single [Category] to [categories]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addCategory(category: Category) = apply { + categories = (categories ?: mutableListOf()).apply { add(category) } + } + + /** + * The end date to retrieve pay statement items by via their last seen pay date in + * `YYYY-MM-DD` format. + */ + fun endDate(endDate: LocalDate?) = apply { this.endDate = endDate } + + /** Alias for calling [Builder.endDate] with `endDate.orElse(null)`. */ + fun endDate(endDate: Optional) = endDate(endDate.getOrNull()) + + /** Case-insensitive partial match search by pay statement item name. */ + fun name(name: String?) = apply { this.name = name } + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) + + /** + * The start date to retrieve pay statement items by via their last seen pay date + * (inclusive) in `YYYY-MM-DD` format. + */ + fun startDate(startDate: LocalDate?) = apply { this.startDate = startDate } + + /** Alias for calling [Builder.startDate] with `startDate.orElse(null)`. */ + fun startDate(startDate: Optional) = startDate(startDate.getOrNull()) + + /** String search by pay statement item type. */ + fun type(type: String?) = apply { this.type = type } + + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [HrisCompanyPayStatementItemListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): HrisCompanyPayStatementItemListParams = + HrisCompanyPayStatementItemListParams( + categories?.toImmutable(), + endDate, + name, + startDate, + type, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + categories?.forEach { put("categories[]", it.toString()) } + endDate?.let { put("end_date", it.toString()) } + name?.let { put("name", it) } + startDate?.let { put("start_date", it.toString()) } + type?.let { put("type", it) } + putAll(additionalQueryParams) + } + .build() + + class Category @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val EARNINGS = of("earnings") + + @JvmField val TAXES = of("taxes") + + @JvmField val EMPLOYEE_DEDUCTIONS = of("employee_deductions") + + @JvmField val EMPLOYER_CONTRIBUTIONS = of("employer_contributions") + + @JvmStatic fun of(value: String) = Category(JsonField.of(value)) + } + + /** An enum containing [Category]'s known values. */ + enum class Known { + EARNINGS, + TAXES, + EMPLOYEE_DEDUCTIONS, + EMPLOYER_CONTRIBUTIONS, + } + + /** + * An enum containing [Category]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Category] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + EARNINGS, + TAXES, + EMPLOYEE_DEDUCTIONS, + EMPLOYER_CONTRIBUTIONS, + /** An enum member indicating that [Category] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + EARNINGS -> Value.EARNINGS + TAXES -> Value.TAXES + EMPLOYEE_DEDUCTIONS -> Value.EMPLOYEE_DEDUCTIONS + EMPLOYER_CONTRIBUTIONS -> Value.EMPLOYER_CONTRIBUTIONS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws FinchInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + EARNINGS -> Known.EARNINGS + TAXES -> Known.TAXES + EMPLOYEE_DEDUCTIONS -> Known.EMPLOYEE_DEDUCTIONS + EMPLOYER_CONTRIBUTIONS -> Known.EMPLOYER_CONTRIBUTIONS + else -> throw FinchInvalidDataException("Unknown Category: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws FinchInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): Category = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Category && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is HrisCompanyPayStatementItemListParams && categories == other.categories && endDate == other.endDate && name == other.name && startDate == other.startDate && type == other.type && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(categories, endDate, name, startDate, type, additionalHeaders, additionalQueryParams) /* spotless:on */ + + override fun toString() = + "HrisCompanyPayStatementItemListParams{categories=$categories, endDate=$endDate, name=$name, startDate=$startDate, type=$type, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleCreateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleCreateParams.kt new file mode 100644 index 00000000..62891454 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleCreateParams.kt @@ -0,0 +1,1459 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.tryfinch.api.core.Enum +import com.tryfinch.api.core.ExcludeMissing +import com.tryfinch.api.core.JsonField +import com.tryfinch.api.core.JsonMissing +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown +import com.tryfinch.api.core.http.Headers +import com.tryfinch.api.core.http.QueryParams +import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Custom rules can be created to associate specific attributes to pay + * statement items depending on the use case. For example, pay statement items that meet certain + * conditions can be labeled as a pre-tax 401k. This metadata can be retrieved where pay statement + * item information is available. + */ +class HrisCompanyPayStatementItemRuleCreateParams +private constructor( + private val body: CreateRuleRequest, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Specifies the fields to be applied when the condition is met. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun attributes(): Optional = body.attributes() + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun conditions(): Optional> = body.conditions() + + /** + * Specifies when the rules should stop applying rules based on the date. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun effectiveEndDate(): Optional = body.effectiveEndDate() + + /** + * Specifies when the rule should begin applying based on the date. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun effectiveStartDate(): Optional = body.effectiveStartDate() + + /** + * The entity type to which the rule is applied. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun entityType(): Optional = body.entityType() + + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _attributes(): JsonField = body._attributes() + + /** + * Returns the raw JSON value of [conditions]. + * + * Unlike [conditions], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _conditions(): JsonField> = body._conditions() + + /** + * Returns the raw JSON value of [effectiveEndDate]. + * + * Unlike [effectiveEndDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _effectiveEndDate(): JsonField = body._effectiveEndDate() + + /** + * Returns the raw JSON value of [effectiveStartDate]. + * + * Unlike [effectiveStartDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _effectiveStartDate(): JsonField = body._effectiveStartDate() + + /** + * Returns the raw JSON value of [entityType]. + * + * Unlike [entityType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _entityType(): JsonField = body._entityType() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + fun _additionalHeaders(): Headers = additionalHeaders + + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): HrisCompanyPayStatementItemRuleCreateParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of + * [HrisCompanyPayStatementItemRuleCreateParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [HrisCompanyPayStatementItemRuleCreateParams]. */ + class Builder internal constructor() { + + private var body: CreateRuleRequest.Builder = CreateRuleRequest.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from( + hrisCompanyPayStatementItemRuleCreateParams: HrisCompanyPayStatementItemRuleCreateParams + ) = apply { + body = hrisCompanyPayStatementItemRuleCreateParams.body.toBuilder() + additionalHeaders = + hrisCompanyPayStatementItemRuleCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = + hrisCompanyPayStatementItemRuleCreateParams.additionalQueryParams.toBuilder() + } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [attributes] + * - [conditions] + * - [effectiveEndDate] + * - [effectiveStartDate] + * - [entityType] + * - etc. + */ + fun body(body: CreateRuleRequest) = apply { this.body = body.toBuilder() } + + /** Specifies the fields to be applied when the condition is met. */ + fun attributes(attributes: Attributes) = apply { body.attributes(attributes) } + + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun attributes(attributes: JsonField) = apply { body.attributes(attributes) } + + fun conditions(conditions: List) = apply { body.conditions(conditions) } + + /** + * Sets [Builder.conditions] to an arbitrary JSON value. + * + * You should usually call [Builder.conditions] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun conditions(conditions: JsonField>) = apply { + body.conditions(conditions) + } + + /** + * Adds a single [Condition] to [conditions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addCondition(condition: Condition) = apply { body.addCondition(condition) } + + /** Specifies when the rules should stop applying rules based on the date. */ + fun effectiveEndDate(effectiveEndDate: String?) = apply { + body.effectiveEndDate(effectiveEndDate) + } + + /** Alias for calling [Builder.effectiveEndDate] with `effectiveEndDate.orElse(null)`. */ + fun effectiveEndDate(effectiveEndDate: Optional) = + effectiveEndDate(effectiveEndDate.getOrNull()) + + /** + * Sets [Builder.effectiveEndDate] to an arbitrary JSON value. + * + * You should usually call [Builder.effectiveEndDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun effectiveEndDate(effectiveEndDate: JsonField) = apply { + body.effectiveEndDate(effectiveEndDate) + } + + /** Specifies when the rule should begin applying based on the date. */ + fun effectiveStartDate(effectiveStartDate: String?) = apply { + body.effectiveStartDate(effectiveStartDate) + } + + /** + * Alias for calling [Builder.effectiveStartDate] with `effectiveStartDate.orElse(null)`. + */ + fun effectiveStartDate(effectiveStartDate: Optional) = + effectiveStartDate(effectiveStartDate.getOrNull()) + + /** + * Sets [Builder.effectiveStartDate] to an arbitrary JSON value. + * + * You should usually call [Builder.effectiveStartDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun effectiveStartDate(effectiveStartDate: JsonField) = apply { + body.effectiveStartDate(effectiveStartDate) + } + + /** The entity type to which the rule is applied. */ + fun entityType(entityType: EntityType) = apply { body.entityType(entityType) } + + /** + * Sets [Builder.entityType] to an arbitrary JSON value. + * + * You should usually call [Builder.entityType] with a well-typed [EntityType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun entityType(entityType: JsonField) = apply { body.entityType(entityType) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [HrisCompanyPayStatementItemRuleCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): HrisCompanyPayStatementItemRuleCreateParams = + HrisCompanyPayStatementItemRuleCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): CreateRuleRequest = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class CreateRuleRequest + private constructor( + private val attributes: JsonField, + private val conditions: JsonField>, + private val effectiveEndDate: JsonField, + private val effectiveStartDate: JsonField, + private val entityType: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("conditions") + @ExcludeMissing + conditions: JsonField> = JsonMissing.of(), + @JsonProperty("effective_end_date") + @ExcludeMissing + effectiveEndDate: JsonField = JsonMissing.of(), + @JsonProperty("effective_start_date") + @ExcludeMissing + effectiveStartDate: JsonField = JsonMissing.of(), + @JsonProperty("entity_type") + @ExcludeMissing + entityType: JsonField = JsonMissing.of(), + ) : this( + attributes, + conditions, + effectiveEndDate, + effectiveStartDate, + entityType, + mutableMapOf(), + ) + + /** + * Specifies the fields to be applied when the condition is met. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun conditions(): Optional> = conditions.getOptional("conditions") + + /** + * Specifies when the rules should stop applying rules based on the date. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun effectiveEndDate(): Optional = + effectiveEndDate.getOptional("effective_end_date") + + /** + * Specifies when the rule should begin applying based on the date. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun effectiveStartDate(): Optional = + effectiveStartDate.getOptional("effective_start_date") + + /** + * The entity type to which the rule is applied. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun entityType(): Optional = entityType.getOptional("entity_type") + + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("attributes") + @ExcludeMissing + fun _attributes(): JsonField = attributes + + /** + * Returns the raw JSON value of [conditions]. + * + * Unlike [conditions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("conditions") + @ExcludeMissing + fun _conditions(): JsonField> = conditions + + /** + * Returns the raw JSON value of [effectiveEndDate]. + * + * Unlike [effectiveEndDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("effective_end_date") + @ExcludeMissing + fun _effectiveEndDate(): JsonField = effectiveEndDate + + /** + * Returns the raw JSON value of [effectiveStartDate]. + * + * Unlike [effectiveStartDate], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("effective_start_date") + @ExcludeMissing + fun _effectiveStartDate(): JsonField = effectiveStartDate + + /** + * Returns the raw JSON value of [entityType]. + * + * Unlike [entityType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("entity_type") + @ExcludeMissing + fun _entityType(): JsonField = entityType + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [CreateRuleRequest]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CreateRuleRequest]. */ + class Builder internal constructor() { + + private var attributes: JsonField = JsonMissing.of() + private var conditions: JsonField>? = null + private var effectiveEndDate: JsonField = JsonMissing.of() + private var effectiveStartDate: JsonField = JsonMissing.of() + private var entityType: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(createRuleRequest: CreateRuleRequest) = apply { + attributes = createRuleRequest.attributes + conditions = createRuleRequest.conditions.map { it.toMutableList() } + effectiveEndDate = createRuleRequest.effectiveEndDate + effectiveStartDate = createRuleRequest.effectiveStartDate + entityType = createRuleRequest.entityType + additionalProperties = createRuleRequest.additionalProperties.toMutableMap() + } + + /** Specifies the fields to be applied when the condition is met. */ + fun attributes(attributes: Attributes) = attributes(JsonField.of(attributes)) + + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun attributes(attributes: JsonField) = apply { + this.attributes = attributes + } + + fun conditions(conditions: List) = conditions(JsonField.of(conditions)) + + /** + * Sets [Builder.conditions] to an arbitrary JSON value. + * + * You should usually call [Builder.conditions] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun conditions(conditions: JsonField>) = apply { + this.conditions = conditions.map { it.toMutableList() } + } + + /** + * Adds a single [Condition] to [conditions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addCondition(condition: Condition) = apply { + conditions = + (conditions ?: JsonField.of(mutableListOf())).also { + checkKnown("conditions", it).add(condition) + } + } + + /** Specifies when the rules should stop applying rules based on the date. */ + fun effectiveEndDate(effectiveEndDate: String?) = + effectiveEndDate(JsonField.ofNullable(effectiveEndDate)) + + /** + * Alias for calling [Builder.effectiveEndDate] with `effectiveEndDate.orElse(null)`. + */ + fun effectiveEndDate(effectiveEndDate: Optional) = + effectiveEndDate(effectiveEndDate.getOrNull()) + + /** + * Sets [Builder.effectiveEndDate] to an arbitrary JSON value. + * + * You should usually call [Builder.effectiveEndDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun effectiveEndDate(effectiveEndDate: JsonField) = apply { + this.effectiveEndDate = effectiveEndDate + } + + /** Specifies when the rule should begin applying based on the date. */ + fun effectiveStartDate(effectiveStartDate: String?) = + effectiveStartDate(JsonField.ofNullable(effectiveStartDate)) + + /** + * Alias for calling [Builder.effectiveStartDate] with + * `effectiveStartDate.orElse(null)`. + */ + fun effectiveStartDate(effectiveStartDate: Optional) = + effectiveStartDate(effectiveStartDate.getOrNull()) + + /** + * Sets [Builder.effectiveStartDate] to an arbitrary JSON value. + * + * You should usually call [Builder.effectiveStartDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun effectiveStartDate(effectiveStartDate: JsonField) = apply { + this.effectiveStartDate = effectiveStartDate + } + + /** The entity type to which the rule is applied. */ + fun entityType(entityType: EntityType) = entityType(JsonField.of(entityType)) + + /** + * Sets [Builder.entityType] to an arbitrary JSON value. + * + * You should usually call [Builder.entityType] with a well-typed [EntityType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun entityType(entityType: JsonField) = apply { + this.entityType = entityType + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CreateRuleRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CreateRuleRequest = + CreateRuleRequest( + attributes, + (conditions ?: JsonMissing.of()).map { it.toImmutable() }, + effectiveEndDate, + effectiveStartDate, + entityType, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): CreateRuleRequest = apply { + if (validated) { + return@apply + } + + attributes().ifPresent { it.validate() } + conditions().ifPresent { it.forEach { it.validate() } } + effectiveEndDate() + effectiveStartDate() + entityType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (conditions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (effectiveEndDate.asKnown().isPresent) 1 else 0) + + (if (effectiveStartDate.asKnown().isPresent) 1 else 0) + + (entityType.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is CreateRuleRequest && attributes == other.attributes && conditions == other.conditions && effectiveEndDate == other.effectiveEndDate && effectiveStartDate == other.effectiveStartDate && entityType == other.entityType && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(attributes, conditions, effectiveEndDate, effectiveStartDate, entityType, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CreateRuleRequest{attributes=$attributes, conditions=$conditions, effectiveEndDate=$effectiveEndDate, effectiveStartDate=$effectiveStartDate, entityType=$entityType, additionalProperties=$additionalProperties}" + } + + /** Specifies the fields to be applied when the condition is met. */ + class Attributes + private constructor( + private val metadata: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values can + * be of any type (string, number, boolean, object, array, etc.). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Attributes]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Attributes]. */ + class Builder internal constructor() { + + private var metadata: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(attributes: Attributes) = apply { + metadata = attributes.metadata + additionalProperties = attributes.additionalProperties.toMutableMap() + } + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values + * can be of any type (string, number, boolean, object, array, etc.). + */ + fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Attributes = Attributes(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values can + * be of any type (string, number, boolean, object, array, etc.). + */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Metadata && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Attributes && metadata == other.metadata && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(metadata, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Attributes{metadata=$metadata, additionalProperties=$additionalProperties}" + } + + class Condition + private constructor( + private val field: JsonField, + private val operator: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("field") @ExcludeMissing field: JsonField = JsonMissing.of(), + @JsonProperty("operator") + @ExcludeMissing + operator: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + ) : this(field, operator, value, mutableMapOf()) + + /** + * The field to be checked in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun field(): Optional = field.getOptional("field") + + /** + * The operator to be used in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun operator(): Optional = operator.getOptional("operator") + + /** + * The value of the field to be checked in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun value(): Optional = value.getOptional("value") + + /** + * Returns the raw JSON value of [field]. + * + * Unlike [field], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("field") @ExcludeMissing fun _field(): JsonField = field + + /** + * Returns the raw JSON value of [operator]. + * + * Unlike [operator], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("operator") @ExcludeMissing fun _operator(): JsonField = operator + + /** + * Returns the raw JSON value of [value]. + * + * Unlike [value], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Condition]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Condition]. */ + class Builder internal constructor() { + + private var field: JsonField = JsonMissing.of() + private var operator: JsonField = JsonMissing.of() + private var value: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(condition: Condition) = apply { + field = condition.field + operator = condition.operator + value = condition.value + additionalProperties = condition.additionalProperties.toMutableMap() + } + + /** The field to be checked in the rule. */ + fun field(field: String) = field(JsonField.of(field)) + + /** + * Sets [Builder.field] to an arbitrary JSON value. + * + * You should usually call [Builder.field] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun field(field: JsonField) = apply { this.field = field } + + /** The operator to be used in the rule. */ + fun operator(operator: Operator) = operator(JsonField.of(operator)) + + /** + * Sets [Builder.operator] to an arbitrary JSON value. + * + * You should usually call [Builder.operator] with a well-typed [Operator] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun operator(operator: JsonField) = apply { this.operator = operator } + + /** The value of the field to be checked in the rule. */ + fun value(value: String) = value(JsonField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary JSON value. + * + * You should usually call [Builder.value] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun value(value: JsonField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Condition]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Condition = + Condition(field, operator, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Condition = apply { + if (validated) { + return@apply + } + + field() + operator().ifPresent { it.validate() } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (field.asKnown().isPresent) 1 else 0) + + (operator.asKnown().getOrNull()?.validity() ?: 0) + + (if (value.asKnown().isPresent) 1 else 0) + + /** The operator to be used in the rule. */ + class Operator @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val EQUALS = of("equals") + + @JvmStatic fun of(value: String) = Operator(JsonField.of(value)) + } + + /** An enum containing [Operator]'s known values. */ + enum class Known { + EQUALS + } + + /** + * An enum containing [Operator]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Operator] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + EQUALS, + /** + * An enum member indicating that [Operator] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + EQUALS -> Value.EQUALS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws FinchInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + EQUALS -> Known.EQUALS + else -> throw FinchInvalidDataException("Unknown Operator: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws FinchInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + FinchInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Operator = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Operator && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Condition && field == other.field && operator == other.operator && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(field, operator, value, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Condition{field=$field, operator=$operator, value=$value, additionalProperties=$additionalProperties}" + } + + /** The entity type to which the rule is applied. */ + class EntityType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PAY_STATEMENT_ITEM = of("pay_statement_item") + + @JvmStatic fun of(value: String) = EntityType(JsonField.of(value)) + } + + /** An enum containing [EntityType]'s known values. */ + enum class Known { + PAY_STATEMENT_ITEM + } + + /** + * An enum containing [EntityType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [EntityType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PAY_STATEMENT_ITEM, + /** + * An enum member indicating that [EntityType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PAY_STATEMENT_ITEM -> Value.PAY_STATEMENT_ITEM + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws FinchInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + PAY_STATEMENT_ITEM -> Known.PAY_STATEMENT_ITEM + else -> throw FinchInvalidDataException("Unknown EntityType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws FinchInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): EntityType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is EntityType && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is HrisCompanyPayStatementItemRuleCreateParams && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(body, additionalHeaders, additionalQueryParams) /* spotless:on */ + + override fun toString() = + "HrisCompanyPayStatementItemRuleCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleDeleteParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleDeleteParams.kt new file mode 100644 index 00000000..a9f7f64d --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleDeleteParams.kt @@ -0,0 +1,239 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkRequired +import com.tryfinch.api.core.http.Headers +import com.tryfinch.api.core.http.QueryParams +import com.tryfinch.api.core.toImmutable +import java.util.Objects +import java.util.Optional + +/** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Delete a rule for a pay statement item. + */ +class HrisCompanyPayStatementItemRuleDeleteParams +private constructor( + private val ruleId: String, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + fun ruleId(): String = ruleId + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + fun _additionalHeaders(): Headers = additionalHeaders + + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [HrisCompanyPayStatementItemRuleDeleteParams]. + * + * The following fields are required: + * ```java + * .ruleId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [HrisCompanyPayStatementItemRuleDeleteParams]. */ + class Builder internal constructor() { + + private var ruleId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from( + hrisCompanyPayStatementItemRuleDeleteParams: HrisCompanyPayStatementItemRuleDeleteParams + ) = apply { + ruleId = hrisCompanyPayStatementItemRuleDeleteParams.ruleId + additionalHeaders = + hrisCompanyPayStatementItemRuleDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = + hrisCompanyPayStatementItemRuleDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = + hrisCompanyPayStatementItemRuleDeleteParams.additionalBodyProperties.toMutableMap() + } + + fun ruleId(ruleId: String) = apply { this.ruleId = ruleId } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [HrisCompanyPayStatementItemRuleDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .ruleId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): HrisCompanyPayStatementItemRuleDeleteParams = + HrisCompanyPayStatementItemRuleDeleteParams( + checkRequired("ruleId", ruleId), + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + fun _body(): Optional> = + Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + + fun _pathParam(index: Int): String = + when (index) { + 0 -> ruleId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is HrisCompanyPayStatementItemRuleDeleteParams && ruleId == other.ruleId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(ruleId, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + + override fun toString() = + "HrisCompanyPayStatementItemRuleDeleteParams{ruleId=$ruleId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleListPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleListPage.kt new file mode 100644 index 00000000..cbc32bc7 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleListPage.kt @@ -0,0 +1,194 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.tryfinch.api.core.ExcludeMissing +import com.tryfinch.api.core.JsonField +import com.tryfinch.api.core.JsonMissing +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.errors.FinchInvalidDataException +import com.tryfinch.api.services.blocking.hris.company.payStatementItem.RuleService +import java.util.Collections +import java.util.Objects +import java.util.Optional +import java.util.stream.Stream +import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull + +/** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon List all rules of a connection account. + */ +class HrisCompanyPayStatementItemRuleListPage +private constructor( + private val rulesService: RuleService, + private val params: HrisCompanyPayStatementItemRuleListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun responses(): List = response().responses() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is HrisCompanyPayStatementItemRuleListPage && rulesService == other.rulesService && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(rulesService, params, response) /* spotless:on */ + + override fun toString() = + "HrisCompanyPayStatementItemRuleListPage{rulesService=$rulesService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !responses().isEmpty() + } + + fun getNextPageParams(): Optional { + return Optional.empty() + } + + fun getNextPage(): Optional { + return getNextPageParams().map { rulesService.list(it) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of( + rulesService: RuleService, + params: HrisCompanyPayStatementItemRuleListParams, + response: Response, + ) = HrisCompanyPayStatementItemRuleListPage(rulesService, params, response) + } + + class Response( + private val responses: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("responses") + responses: JsonField> = JsonMissing.of() + ) : this(responses, mutableMapOf()) + + fun responses(): List = + responses.getOptional("responses").getOrNull() ?: listOf() + + @JsonProperty("responses") + fun _responses(): Optional>> = + Optional.ofNullable(responses) + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + private var validated: Boolean = false + + fun validate(): Response = apply { + if (validated) { + return@apply + } + + responses().map { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Response && responses == other.responses && additionalProperties == other.additionalProperties /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(responses, additionalProperties) /* spotless:on */ + + override fun toString() = + "Response{responses=$responses, additionalProperties=$additionalProperties}" + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [HrisCompanyPayStatementItemRuleListPage]. + */ + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var responses: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.responses = page.responses + this.additionalProperties.putAll(page.additionalProperties) + } + + fun responses(responses: List) = responses(JsonField.of(responses)) + + fun responses(responses: JsonField>) = apply { + this.responses = responses + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(responses, additionalProperties.toMutableMap()) + } + } + + class AutoPager(private val firstPage: HrisCompanyPayStatementItemRuleListPage) : + Iterable { + + override fun iterator(): Iterator = iterator { + var page = firstPage + var index = 0 + while (true) { + while (index < page.responses().size) { + yield(page.responses()[index++]) + } + page = page.getNextPage().getOrNull() ?: break + index = 0 + } + } + + fun stream(): Stream { + return StreamSupport.stream(spliterator(), false) + } + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleListPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleListPageAsync.kt new file mode 100644 index 00000000..9b3f21e3 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleListPageAsync.kt @@ -0,0 +1,206 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.tryfinch.api.core.ExcludeMissing +import com.tryfinch.api.core.JsonField +import com.tryfinch.api.core.JsonMissing +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.errors.FinchInvalidDataException +import com.tryfinch.api.services.async.hris.company.payStatementItem.RuleServiceAsync +import java.util.Collections +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull + +/** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon List all rules of a connection account. + */ +class HrisCompanyPayStatementItemRuleListPageAsync +private constructor( + private val rulesService: RuleServiceAsync, + private val params: HrisCompanyPayStatementItemRuleListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun responses(): List = response().responses() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is HrisCompanyPayStatementItemRuleListPageAsync && rulesService == other.rulesService && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(rulesService, params, response) /* spotless:on */ + + override fun toString() = + "HrisCompanyPayStatementItemRuleListPageAsync{rulesService=$rulesService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !responses().isEmpty() + } + + fun getNextPageParams(): Optional { + return Optional.empty() + } + + fun getNextPage(): CompletableFuture> { + return getNextPageParams() + .map { rulesService.list(it).thenApply { Optional.of(it) } } + .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of( + rulesService: RuleServiceAsync, + params: HrisCompanyPayStatementItemRuleListParams, + response: Response, + ) = HrisCompanyPayStatementItemRuleListPageAsync(rulesService, params, response) + } + + class Response( + private val responses: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("responses") + responses: JsonField> = JsonMissing.of() + ) : this(responses, mutableMapOf()) + + fun responses(): List = + responses.getOptional("responses").getOrNull() ?: listOf() + + @JsonProperty("responses") + fun _responses(): Optional>> = + Optional.ofNullable(responses) + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + private var validated: Boolean = false + + fun validate(): Response = apply { + if (validated) { + return@apply + } + + responses().map { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Response && responses == other.responses && additionalProperties == other.additionalProperties /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(responses, additionalProperties) /* spotless:on */ + + override fun toString() = + "Response{responses=$responses, additionalProperties=$additionalProperties}" + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [HrisCompanyPayStatementItemRuleListPageAsync]. + */ + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var responses: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.responses = page.responses + this.additionalProperties.putAll(page.additionalProperties) + } + + fun responses(responses: List) = responses(JsonField.of(responses)) + + fun responses(responses: JsonField>) = apply { + this.responses = responses + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(responses, additionalProperties.toMutableMap()) + } + } + + class AutoPager(private val firstPage: HrisCompanyPayStatementItemRuleListPageAsync) { + + fun forEach( + action: Predicate, + executor: Executor, + ): CompletableFuture { + fun CompletableFuture>.forEach( + action: (RuleListResponse) -> Boolean, + executor: Executor, + ): CompletableFuture = + thenComposeAsync( + { page -> + page + .filter { it.responses().all(action) } + .map { it.getNextPage().forEach(action, executor) } + .orElseGet { CompletableFuture.completedFuture(null) } + }, + executor, + ) + return CompletableFuture.completedFuture(Optional.of(firstPage)) + .forEach(action::test, executor) + } + + fun toList(executor: Executor): CompletableFuture> { + val values = mutableListOf() + return forEach(values::add, executor).thenApply { values } + } + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleListParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleListParams.kt new file mode 100644 index 00000000..a958f121 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleListParams.kt @@ -0,0 +1,179 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.tryfinch.api.core.Params +import com.tryfinch.api.core.http.Headers +import com.tryfinch.api.core.http.QueryParams +import java.util.Objects + +/** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon List all rules of a connection account. + */ +class HrisCompanyPayStatementItemRuleListParams +private constructor( + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + fun _additionalHeaders(): Headers = additionalHeaders + + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): HrisCompanyPayStatementItemRuleListParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of + * [HrisCompanyPayStatementItemRuleListParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [HrisCompanyPayStatementItemRuleListParams]. */ + class Builder internal constructor() { + + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from( + hrisCompanyPayStatementItemRuleListParams: HrisCompanyPayStatementItemRuleListParams + ) = apply { + additionalHeaders = + hrisCompanyPayStatementItemRuleListParams.additionalHeaders.toBuilder() + additionalQueryParams = + hrisCompanyPayStatementItemRuleListParams.additionalQueryParams.toBuilder() + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [HrisCompanyPayStatementItemRuleListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): HrisCompanyPayStatementItemRuleListParams = + HrisCompanyPayStatementItemRuleListParams( + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is HrisCompanyPayStatementItemRuleListParams && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(additionalHeaders, additionalQueryParams) /* spotless:on */ + + override fun toString() = + "HrisCompanyPayStatementItemRuleListParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleUpdateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleUpdateParams.kt new file mode 100644 index 00000000..0ec80b82 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleUpdateParams.kt @@ -0,0 +1,378 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.tryfinch.api.core.ExcludeMissing +import com.tryfinch.api.core.JsonMissing +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkRequired +import com.tryfinch.api.core.http.Headers +import com.tryfinch.api.core.http.QueryParams +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections +import java.util.Objects + +/** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Update a rule for a pay statement item. + */ +class HrisCompanyPayStatementItemRuleUpdateParams +private constructor( + private val ruleId: String, + private val body: UpdateRuleRequest, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + fun ruleId(): String = ruleId + + fun _optionalProperty(): JsonValue = body._optionalProperty() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + fun _additionalHeaders(): Headers = additionalHeaders + + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [HrisCompanyPayStatementItemRuleUpdateParams]. + * + * The following fields are required: + * ```java + * .ruleId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [HrisCompanyPayStatementItemRuleUpdateParams]. */ + class Builder internal constructor() { + + private var ruleId: String? = null + private var body: UpdateRuleRequest.Builder = UpdateRuleRequest.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from( + hrisCompanyPayStatementItemRuleUpdateParams: HrisCompanyPayStatementItemRuleUpdateParams + ) = apply { + ruleId = hrisCompanyPayStatementItemRuleUpdateParams.ruleId + body = hrisCompanyPayStatementItemRuleUpdateParams.body.toBuilder() + additionalHeaders = + hrisCompanyPayStatementItemRuleUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = + hrisCompanyPayStatementItemRuleUpdateParams.additionalQueryParams.toBuilder() + } + + fun ruleId(ruleId: String) = apply { this.ruleId = ruleId } + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [optionalProperty] + */ + fun body(body: UpdateRuleRequest) = apply { this.body = body.toBuilder() } + + fun optionalProperty(optionalProperty: JsonValue) = apply { + body.optionalProperty(optionalProperty) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [HrisCompanyPayStatementItemRuleUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .ruleId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): HrisCompanyPayStatementItemRuleUpdateParams = + HrisCompanyPayStatementItemRuleUpdateParams( + checkRequired("ruleId", ruleId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): UpdateRuleRequest = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> ruleId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class UpdateRuleRequest + private constructor( + private val optionalProperty: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("optionalProperty") + @ExcludeMissing + optionalProperty: JsonValue = JsonMissing.of() + ) : this(optionalProperty, mutableMapOf()) + + @JsonProperty("optionalProperty") + @ExcludeMissing + fun _optionalProperty(): JsonValue = optionalProperty + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [UpdateRuleRequest]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UpdateRuleRequest]. */ + class Builder internal constructor() { + + private var optionalProperty: JsonValue = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(updateRuleRequest: UpdateRuleRequest) = apply { + optionalProperty = updateRuleRequest.optionalProperty + additionalProperties = updateRuleRequest.additionalProperties.toMutableMap() + } + + fun optionalProperty(optionalProperty: JsonValue) = apply { + this.optionalProperty = optionalProperty + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [UpdateRuleRequest]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UpdateRuleRequest = + UpdateRuleRequest(optionalProperty, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): UpdateRuleRequest = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = 0 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is UpdateRuleRequest && optionalProperty == other.optionalProperty && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(optionalProperty, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "UpdateRuleRequest{optionalProperty=$optionalProperty, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is HrisCompanyPayStatementItemRuleUpdateParams && ruleId == other.ruleId && body == other.body && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(ruleId, body, additionalHeaders, additionalQueryParams) /* spotless:on */ + + override fun toString() = + "HrisCompanyPayStatementItemRuleUpdateParams{ruleId=$ruleId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyRetrieveParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyRetrieveParams.kt index cd51a0ed..ddb27057 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyRetrieveParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisCompanyRetrieveParams.kt @@ -2,7 +2,6 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams @@ -19,21 +18,19 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): HrisCompanyRetrieveParams = builder().build() + /** + * Returns a mutable builder for constructing an instance of [HrisCompanyRetrieveParams]. + */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisCompanyRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var additionalHeaders: Headers.Builder = Headers.builder() @@ -143,10 +140,19 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisCompanyRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): HrisCompanyRetrieveParams = HrisCompanyRetrieveParams(additionalHeaders.build(), additionalQueryParams.build()) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsPage.kt index 4b994a9e..3e7dd7da 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsPage.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsPage.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.blocking.hris.DirectoryService +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull /** Read company directory and organization structure */ @Deprecated("use `list` instead") @@ -32,7 +32,7 @@ private constructor( fun individuals(): List = response().individuals() - fun paging(): Optional = response().paging() + fun paging(): Paging = response().paging() override fun equals(other: Any?): Boolean { if (this === other) { @@ -52,8 +52,8 @@ private constructor( return false } - return paging().flatMap { it.offset() }.orElse(0) + individuals().count() < - paging().flatMap { it.count() }.orElse(Long.MAX_VALUE) + return paging().offset().orElse(0) + individuals().count() < + paging().count().orElse(Long.MAX_VALUE) } fun getNextPageParams(): Optional { @@ -64,7 +64,7 @@ private constructor( return Optional.of( HrisDirectoryListIndividualsParams.builder() .from(params) - .offset(paging().flatMap { it.offset() }.orElse(0) + individuals().count()) + .offset(paging().offset().orElse(0) + individuals().count()) .build() ) } @@ -85,21 +85,23 @@ private constructor( ) = HrisDirectoryListIndividualsPage(directoryService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("individuals") - private val individuals: JsonField> = JsonMissing.of(), - @JsonProperty("paging") private val paging: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val individuals: JsonField>, + private val paging: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("individuals") + individuals: JsonField> = JsonMissing.of(), + @JsonProperty("paging") paging: JsonField = JsonMissing.of(), + ) : this(individuals, paging, mutableMapOf()) + fun individuals(): List = - individuals.getNullable("individuals") ?: listOf() + individuals.getOptional("individuals").getOrNull() ?: listOf() - fun paging(): Optional = Optional.ofNullable(paging.getNullable("paging")) + fun paging(): Paging = paging.getRequired("paging") @JsonProperty("individuals") fun _individuals(): Optional>> = @@ -108,9 +110,15 @@ private constructor( @JsonProperty("paging") fun _paging(): Optional> = Optional.ofNullable(paging) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -120,10 +128,18 @@ private constructor( } individuals().map { it.validate() } - paging().ifPresent { it.validate() } + paging().validate() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -141,6 +157,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisDirectoryListIndividualsPage]. + */ @JvmStatic fun builder() = Builder() } @@ -172,7 +192,13 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(individuals, paging, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = + Response(individuals, paging, additionalProperties.toMutableMap()) } } @@ -186,7 +212,7 @@ private constructor( while (index < page.individuals().size) { yield(page.individuals()[index++]) } - page = page.getNextPage().orElse(null) ?: break + page = page.getNextPage().getOrNull() ?: break index = 0 } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsPageAsync.kt index ca3201d0..cf3abdf6 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsPageAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsPageAsync.kt @@ -10,15 +10,15 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.async.hris.DirectoryServiceAsync +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull /** Read company directory and organization structure */ @Deprecated("use `list` instead") @@ -33,7 +33,7 @@ private constructor( fun individuals(): List = response().individuals() - fun paging(): Optional = response().paging() + fun paging(): Paging = response().paging() override fun equals(other: Any?): Boolean { if (this === other) { @@ -53,8 +53,8 @@ private constructor( return false } - return paging().flatMap { it.offset() }.orElse(0) + individuals().count() < - paging().flatMap { it.count() }.orElse(Long.MAX_VALUE) + return paging().offset().orElse(0) + individuals().count() < + paging().count().orElse(Long.MAX_VALUE) } fun getNextPageParams(): Optional { @@ -65,7 +65,7 @@ private constructor( return Optional.of( HrisDirectoryListIndividualsParams.builder() .from(params) - .offset(paging().flatMap { it.offset() }.orElse(0) + individuals().count()) + .offset(paging().offset().orElse(0) + individuals().count()) .build() ) } @@ -88,21 +88,23 @@ private constructor( ) = HrisDirectoryListIndividualsPageAsync(directoryService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("individuals") - private val individuals: JsonField> = JsonMissing.of(), - @JsonProperty("paging") private val paging: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val individuals: JsonField>, + private val paging: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("individuals") + individuals: JsonField> = JsonMissing.of(), + @JsonProperty("paging") paging: JsonField = JsonMissing.of(), + ) : this(individuals, paging, mutableMapOf()) + fun individuals(): List = - individuals.getNullable("individuals") ?: listOf() + individuals.getOptional("individuals").getOrNull() ?: listOf() - fun paging(): Optional = Optional.ofNullable(paging.getNullable("paging")) + fun paging(): Paging = paging.getRequired("paging") @JsonProperty("individuals") fun _individuals(): Optional>> = @@ -111,9 +113,15 @@ private constructor( @JsonProperty("paging") fun _paging(): Optional> = Optional.ofNullable(paging) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -123,10 +131,18 @@ private constructor( } individuals().map { it.validate() } - paging().ifPresent { it.validate() } + paging().validate() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -144,6 +160,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisDirectoryListIndividualsPageAsync]. + */ @JvmStatic fun builder() = Builder() } @@ -175,7 +195,13 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(individuals, paging, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = + Response(individuals, paging, additionalProperties.toMutableMap()) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsParams.kt index aa21caf7..6975371d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsParams.kt @@ -2,12 +2,12 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Read company directory and organization structure */ @Deprecated("use `list` instead") @@ -29,27 +29,20 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.limit?.let { queryParams.put("limit", listOf(it.toString())) } - this.offset?.let { queryParams.put("offset", listOf(it.toString())) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): HrisDirectoryListIndividualsParams = builder().build() + /** + * Returns a mutable builder for constructing an instance of + * [HrisDirectoryListIndividualsParams]. + */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisDirectoryListIndividualsParams]. */ - @NoAutoDetect class Builder internal constructor() { private var limit: Long? = null @@ -70,22 +63,28 @@ private constructor( /** Number of employees to return (defaults to all) */ fun limit(limit: Long?) = apply { this.limit = limit } - /** Number of employees to return (defaults to all) */ + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun limit(limit: Long) = limit(limit as Long?) - /** Number of employees to return (defaults to all) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun limit(limit: Optional) = limit(limit.orElse(null) as Long?) + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** Index to start from (defaults to 0) */ fun offset(offset: Long?) = apply { this.offset = offset } - /** Index to start from (defaults to 0) */ + /** + * Alias for [Builder.offset]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun offset(offset: Long) = offset(offset as Long?) - /** Index to start from (defaults to 0) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun offset(offset: Optional) = offset(offset.orElse(null) as Long?) + /** Alias for calling [Builder.offset] with `offset.orElse(null)`. */ + fun offset(offset: Optional) = offset(offset.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -185,6 +184,11 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisDirectoryListIndividualsParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): HrisDirectoryListIndividualsParams = HrisDirectoryListIndividualsParams( limit, @@ -194,6 +198,17 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + limit?.let { put("limit", it.toString()) } + offset?.let { put("offset", it.toString()) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListPage.kt index 4a31c2c6..7f5dcd14 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListPage.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListPage.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.blocking.hris.DirectoryService +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull /** Read company directory and organization structure */ class HrisDirectoryListPage @@ -31,7 +31,7 @@ private constructor( fun individuals(): List = response().individuals() - fun paging(): Optional = response().paging() + fun paging(): Paging = response().paging() override fun equals(other: Any?): Boolean { if (this === other) { @@ -51,8 +51,8 @@ private constructor( return false } - return paging().flatMap { it.offset() }.orElse(0) + individuals().count() < - paging().flatMap { it.count() }.orElse(Long.MAX_VALUE) + return paging().offset().orElse(0) + individuals().count() < + paging().count().orElse(Long.MAX_VALUE) } fun getNextPageParams(): Optional { @@ -63,7 +63,7 @@ private constructor( return Optional.of( HrisDirectoryListParams.builder() .from(params) - .offset(paging().flatMap { it.offset() }.orElse(0) + individuals().count()) + .offset(paging().offset().orElse(0) + individuals().count()) .build() ) } @@ -84,21 +84,23 @@ private constructor( ) = HrisDirectoryListPage(directoryService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("individuals") - private val individuals: JsonField> = JsonMissing.of(), - @JsonProperty("paging") private val paging: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val individuals: JsonField>, + private val paging: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("individuals") + individuals: JsonField> = JsonMissing.of(), + @JsonProperty("paging") paging: JsonField = JsonMissing.of(), + ) : this(individuals, paging, mutableMapOf()) + fun individuals(): List = - individuals.getNullable("individuals") ?: listOf() + individuals.getOptional("individuals").getOrNull() ?: listOf() - fun paging(): Optional = Optional.ofNullable(paging.getNullable("paging")) + fun paging(): Paging = paging.getRequired("paging") @JsonProperty("individuals") fun _individuals(): Optional>> = @@ -107,9 +109,15 @@ private constructor( @JsonProperty("paging") fun _paging(): Optional> = Optional.ofNullable(paging) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -119,10 +127,18 @@ private constructor( } individuals().map { it.validate() } - paging().ifPresent { it.validate() } + paging().validate() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -140,6 +156,9 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of [HrisDirectoryListPage]. + */ @JvmStatic fun builder() = Builder() } @@ -171,7 +190,13 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(individuals, paging, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = + Response(individuals, paging, additionalProperties.toMutableMap()) } } @@ -185,7 +210,7 @@ private constructor( while (index < page.individuals().size) { yield(page.individuals()[index++]) } - page = page.getNextPage().orElse(null) ?: break + page = page.getNextPage().getOrNull() ?: break index = 0 } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListPageAsync.kt index 861ffde7..44ea4e6e 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListPageAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListPageAsync.kt @@ -10,15 +10,15 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.async.hris.DirectoryServiceAsync +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull /** Read company directory and organization structure */ class HrisDirectoryListPageAsync @@ -32,7 +32,7 @@ private constructor( fun individuals(): List = response().individuals() - fun paging(): Optional = response().paging() + fun paging(): Paging = response().paging() override fun equals(other: Any?): Boolean { if (this === other) { @@ -52,8 +52,8 @@ private constructor( return false } - return paging().flatMap { it.offset() }.orElse(0) + individuals().count() < - paging().flatMap { it.count() }.orElse(Long.MAX_VALUE) + return paging().offset().orElse(0) + individuals().count() < + paging().count().orElse(Long.MAX_VALUE) } fun getNextPageParams(): Optional { @@ -64,7 +64,7 @@ private constructor( return Optional.of( HrisDirectoryListParams.builder() .from(params) - .offset(paging().flatMap { it.offset() }.orElse(0) + individuals().count()) + .offset(paging().offset().orElse(0) + individuals().count()) .build() ) } @@ -87,21 +87,23 @@ private constructor( ) = HrisDirectoryListPageAsync(directoryService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("individuals") - private val individuals: JsonField> = JsonMissing.of(), - @JsonProperty("paging") private val paging: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val individuals: JsonField>, + private val paging: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("individuals") + individuals: JsonField> = JsonMissing.of(), + @JsonProperty("paging") paging: JsonField = JsonMissing.of(), + ) : this(individuals, paging, mutableMapOf()) + fun individuals(): List = - individuals.getNullable("individuals") ?: listOf() + individuals.getOptional("individuals").getOrNull() ?: listOf() - fun paging(): Optional = Optional.ofNullable(paging.getNullable("paging")) + fun paging(): Paging = paging.getRequired("paging") @JsonProperty("individuals") fun _individuals(): Optional>> = @@ -110,9 +112,15 @@ private constructor( @JsonProperty("paging") fun _paging(): Optional> = Optional.ofNullable(paging) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -122,10 +130,18 @@ private constructor( } individuals().map { it.validate() } - paging().ifPresent { it.validate() } + paging().validate() validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -143,6 +159,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisDirectoryListPageAsync]. + */ @JvmStatic fun builder() = Builder() } @@ -174,7 +194,13 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(individuals, paging, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = + Response(individuals, paging, additionalProperties.toMutableMap()) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListParams.kt index ed4d67ad..be838dc8 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDirectoryListParams.kt @@ -2,12 +2,12 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Read company directory and organization structure */ class HrisDirectoryListParams @@ -28,27 +28,17 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.limit?.let { queryParams.put("limit", listOf(it.toString())) } - this.offset?.let { queryParams.put("offset", listOf(it.toString())) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): HrisDirectoryListParams = builder().build() + /** Returns a mutable builder for constructing an instance of [HrisDirectoryListParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisDirectoryListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var limit: Long? = null @@ -67,22 +57,28 @@ private constructor( /** Number of employees to return (defaults to all) */ fun limit(limit: Long?) = apply { this.limit = limit } - /** Number of employees to return (defaults to all) */ + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun limit(limit: Long) = limit(limit as Long?) - /** Number of employees to return (defaults to all) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun limit(limit: Optional) = limit(limit.orElse(null) as Long?) + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** Index to start from (defaults to 0) */ fun offset(offset: Long?) = apply { this.offset = offset } - /** Index to start from (defaults to 0) */ + /** + * Alias for [Builder.offset]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun offset(offset: Long) = offset(offset as Long?) - /** Index to start from (defaults to 0) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun offset(offset: Optional) = offset(offset.orElse(null) as Long?) + /** Alias for calling [Builder.offset] with `offset.orElse(null)`. */ + fun offset(offset: Optional) = offset(offset.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -182,6 +178,11 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisDirectoryListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): HrisDirectoryListParams = HrisDirectoryListParams( limit, @@ -191,6 +192,17 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + limit?.let { put("limit", it.toString()) } + offset?.let { put("offset", it.toString()) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDocumentListParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDocumentListParams.kt index 8e51b518..dd322628 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDocumentListParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDocumentListParams.kt @@ -5,7 +5,6 @@ package com.tryfinch.api.models import com.fasterxml.jackson.annotation.JsonCreator import com.tryfinch.api.core.Enum import com.tryfinch.api.core.JsonField -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams @@ -13,6 +12,7 @@ import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** **Beta:** This endpoint is in beta and may change. Retrieve a list of company-wide documents. */ class HrisDocumentListParams @@ -44,29 +44,17 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.individualIds?.let { queryParams.put("individual_ids[]", it.map(Any::toString)) } - this.limit?.let { queryParams.put("limit", listOf(it.toString())) } - this.offset?.let { queryParams.put("offset", listOf(it.toString())) } - this.types?.let { queryParams.put("types[]", it.map(Any::toString)) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): HrisDocumentListParams = builder().build() + /** Returns a mutable builder for constructing an instance of [HrisDocumentListParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisDocumentListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var individualIds: MutableList? = null @@ -94,16 +82,14 @@ private constructor( this.individualIds = individualIds?.toMutableList() } - /** - * Comma-delimited list of stable Finch uuids for each individual. If empty, defaults to all - * individuals - */ + /** Alias for calling [Builder.individualIds] with `individualIds.orElse(null)`. */ fun individualIds(individualIds: Optional>) = - individualIds(individualIds.orElse(null)) + individualIds(individualIds.getOrNull()) /** - * Comma-delimited list of stable Finch uuids for each individual. If empty, defaults to all - * individuals + * Adds a single [String] to [individualIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. */ fun addIndividualId(individualId: String) = apply { individualIds = (individualIds ?: mutableListOf()).apply { add(individualId) } @@ -112,30 +98,40 @@ private constructor( /** Number of documents to return (defaults to all) */ fun limit(limit: Long?) = apply { this.limit = limit } - /** Number of documents to return (defaults to all) */ + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun limit(limit: Long) = limit(limit as Long?) - /** Number of documents to return (defaults to all) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun limit(limit: Optional) = limit(limit.orElse(null) as Long?) + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** Index to start from (defaults to 0) */ fun offset(offset: Long?) = apply { this.offset = offset } - /** Index to start from (defaults to 0) */ + /** + * Alias for [Builder.offset]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun offset(offset: Long) = offset(offset as Long?) - /** Index to start from (defaults to 0) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun offset(offset: Optional) = offset(offset.orElse(null) as Long?) + /** Alias for calling [Builder.offset] with `offset.orElse(null)`. */ + fun offset(offset: Optional) = offset(offset.getOrNull()) /** Comma-delimited list of document types to filter on. If empty, defaults to all types */ fun types(types: List?) = apply { this.types = types?.toMutableList() } - /** Comma-delimited list of document types to filter on. If empty, defaults to all types */ - fun types(types: Optional>) = types(types.orElse(null)) + /** Alias for calling [Builder.types] with `types.orElse(null)`. */ + fun types(types: Optional>) = types(types.getOrNull()) - /** Comma-delimited list of document types to filter on. If empty, defaults to all types */ + /** + * Adds a single [Type] to [types]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addType(type: Type) = apply { types = (types ?: mutableListOf()).apply { add(type) } } fun additionalHeaders(additionalHeaders: Headers) = apply { @@ -236,6 +232,11 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisDocumentListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): HrisDocumentListParams = HrisDocumentListParams( individualIds?.toImmutable(), @@ -247,6 +248,19 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + individualIds?.forEach { put("individual_ids[]", it) } + limit?.let { put("limit", it.toString()) } + offset?.let { put("offset", it.toString()) } + types?.forEach { put("types[]", it.toString()) } + putAll(additionalQueryParams) + } + .build() + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -331,6 +345,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDocumentRetreiveParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDocumentRetreiveParams.kt index 5fbb6079..5de75843 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDocumentRetreiveParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisDocumentRetreiveParams.kt @@ -2,7 +2,6 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers @@ -26,26 +25,22 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> documentId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [HrisDocumentRetreiveParams]. + * + * The following fields are required: + * ```java + * .documentId() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisDocumentRetreiveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var documentId: String? = null @@ -159,6 +154,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisDocumentRetreiveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .documentId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): HrisDocumentRetreiveParams = HrisDocumentRetreiveParams( checkRequired("documentId", documentId), @@ -167,6 +174,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> documentId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyPage.kt index fb7c68c0..eae6a1f5 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyPage.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyPage.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.blocking.hris.EmploymentService +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull /** Read individual employment and income data */ class HrisEmploymentRetrieveManyPage @@ -68,26 +68,33 @@ private constructor( ) = HrisEmploymentRetrieveManyPage(employmentsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("responses") - private val responses: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val responses: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("responses") + responses: JsonField> = JsonMissing.of() + ) : this(responses, mutableMapOf()) + fun responses(): List = - responses.getNullable("responses") ?: listOf() + responses.getOptional("responses").getOrNull() ?: listOf() @JsonProperty("responses") fun _responses(): Optional>> = Optional.ofNullable(responses) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -100,6 +107,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -117,6 +132,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisEmploymentRetrieveManyPage]. + */ @JvmStatic fun builder() = Builder() } @@ -142,7 +161,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(responses, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(responses, additionalProperties.toMutableMap()) } } @@ -156,7 +180,7 @@ private constructor( while (index < page.responses().size) { yield(page.responses()[index++]) } - page = page.getNextPage().orElse(null) ?: break + page = page.getNextPage().getOrNull() ?: break index = 0 } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyPageAsync.kt index 16233a7b..b786e90f 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyPageAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyPageAsync.kt @@ -10,15 +10,15 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.async.hris.EmploymentServiceAsync +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull /** Read individual employment and income data */ class HrisEmploymentRetrieveManyPageAsync @@ -71,26 +71,33 @@ private constructor( ) = HrisEmploymentRetrieveManyPageAsync(employmentsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("responses") - private val responses: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val responses: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("responses") + responses: JsonField> = JsonMissing.of() + ) : this(responses, mutableMapOf()) + fun responses(): List = - responses.getNullable("responses") ?: listOf() + responses.getOptional("responses").getOrNull() ?: listOf() @JsonProperty("responses") fun _responses(): Optional>> = Optional.ofNullable(responses) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -103,6 +110,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -120,6 +135,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisEmploymentRetrieveManyPageAsync]. + */ @JvmStatic fun builder() = Builder() } @@ -145,7 +164,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(responses, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(responses, additionalProperties.toMutableMap()) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyParams.kt index 7dc8e0fa..869a198d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyParams.kt @@ -10,14 +10,16 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects +import kotlin.jvm.optionals.getOrNull /** Read individual employment and income data */ class HrisEmploymentRetrieveManyParams @@ -27,10 +29,19 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { - /** The array of batch requests. */ + /** + * The array of batch requests. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun requests(): List = body.requests() - /** The array of batch requests. */ + /** + * Returns the raw JSON value of [requests]. + * + * Unlike [requests], this method doesn't throw if the JSON field has an unexpected type. + */ fun _requests(): JsonField> = body._requests() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -39,141 +50,23 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - /** Individual Ids Request Body */ - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("requests") - @ExcludeMissing - private val requests: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** The array of batch requests. */ - fun requests(): List = requests.getRequired("requests") - - /** The array of batch requests. */ - @JsonProperty("requests") - @ExcludeMissing - fun _requests(): JsonField> = requests - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - requests().forEach { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var requests: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - requests = body.requests.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** The array of batch requests. */ - fun requests(requests: List) = requests(JsonField.of(requests)) - - /** The array of batch requests. */ - fun requests(requests: JsonField>) = apply { - this.requests = requests.map { it.toMutableList() } - } - - /** The array of batch requests. */ - fun addRequest(request: Request) = apply { - requests = - (requests ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(request) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = - Body( - checkRequired("requests", requests).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && requests == other.requests && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(requests, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{requests=$requests, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisEmploymentRetrieveManyParams]. + * + * The following fields are required: + * ```java + * .requests() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisEmploymentRetrieveManyParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -189,13 +82,32 @@ private constructor( hrisEmploymentRetrieveManyParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [requests] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** The array of batch requests. */ fun requests(requests: List) = apply { body.requests(requests) } - /** The array of batch requests. */ + /** + * Sets [Builder.requests] to an arbitrary JSON value. + * + * You should usually call [Builder.requests] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun requests(requests: JsonField>) = apply { body.requests(requests) } - /** The array of batch requests. */ + /** + * Adds a single [Request] to [requests]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addRequest(request: Request) = apply { body.addRequest(request) } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { @@ -315,6 +227,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisEmploymentRetrieveManyParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .requests() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): HrisEmploymentRetrieveManyParams = HrisEmploymentRetrieveManyParams( body.build(), @@ -323,52 +247,246 @@ private constructor( ) } - @NoAutoDetect - class Request - @JsonCreator + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + /** Individual Ids Request Body */ + class Body private constructor( - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val requests: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("requests") + @ExcludeMissing + requests: JsonField> = JsonMissing.of() + ) : this(requests, mutableMapOf()) + /** - * A stable Finch `id` (UUID v4) for an individual in the company. There is no limit to the - * number of `individual_id` to send per request. It is preferantial to send all ids in a - * single request for Finch to optimize provider rate-limits. + * The array of batch requests. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). */ - fun individualId(): String = individualId.getRequired("individual_id") + fun requests(): List = requests.getRequired("requests") /** - * A stable Finch `id` (UUID v4) for an individual in the company. There is no limit to the - * number of `individual_id` to send per request. It is preferantial to send all ids in a - * single request for Finch to optimize provider rate-limits. + * Returns the raw JSON value of [requests]. + * + * Unlike [requests], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("individual_id") + @JsonProperty("requests") @ExcludeMissing - fun _individualId(): JsonField = individualId + fun _requests(): JsonField> = requests + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .requests() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var requests: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + requests = body.requests.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The array of batch requests. */ + fun requests(requests: List) = requests(JsonField.of(requests)) + + /** + * Sets [Builder.requests] to an arbitrary JSON value. + * + * You should usually call [Builder.requests] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun requests(requests: JsonField>) = apply { + this.requests = requests.map { it.toMutableList() } + } + + /** + * Adds a single [Request] to [requests]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addRequest(request: Request) = apply { + requests = + (requests ?: JsonField.of(mutableListOf())).also { + checkKnown("requests", it).add(request) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .requests() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("requests", requests).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } private var validated: Boolean = false - fun validate(): Request = apply { + fun validate(): Body = apply { if (validated) { return@apply } - individualId() + requests().forEach { it.validate() } validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (requests.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && requests == other.requests && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(requests, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{requests=$requests, additionalProperties=$additionalProperties}" + } + + class Request + private constructor( + private val individualId: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of() + ) : this(individualId, mutableMapOf()) + + /** + * A stable Finch `id` (UUID v4) for an individual in the company. There is no limit to the + * number of `individual_id` to send per request. It is preferantial to send all ids in a + * single request for Finch to optimize provider rate-limits. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun individualId(): String = individualId.getRequired("individual_id") + + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("individual_id") + @ExcludeMissing + fun _individualId(): JsonField = individualId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Request]. + * + * The following fields are required: + * ```java + * .individualId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -392,9 +510,11 @@ private constructor( fun individualId(individualId: String) = individualId(JsonField.of(individualId)) /** - * A stable Finch `id` (UUID v4) for an individual in the company. There is no limit to - * the number of `individual_id` to send per request. It is preferantial to send all ids - * in a single request for Finch to optimize provider rate-limits. + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId @@ -419,13 +539,53 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Request]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .individualId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Request = Request( checkRequired("individualId", individualId), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Request = apply { + if (validated) { + return@apply + } + + individualId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (individualId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyPage.kt index 580aacb5..9b2e156d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyPage.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyPage.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.blocking.hris.IndividualService +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull /** Read individual data, excluding income and employment data */ class HrisIndividualRetrieveManyPage @@ -68,25 +68,33 @@ private constructor( ) = HrisIndividualRetrieveManyPage(individualsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("responses") - private val responses: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val responses: JsonField>, + private val additionalProperties: MutableMap, ) { - fun responses(): List = responses.getNullable("responses") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("responses") + responses: JsonField> = JsonMissing.of() + ) : this(responses, mutableMapOf()) + + fun responses(): List = + responses.getOptional("responses").getOrNull() ?: listOf() @JsonProperty("responses") fun _responses(): Optional>> = Optional.ofNullable(responses) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -99,6 +107,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -116,6 +132,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisIndividualRetrieveManyPage]. + */ @JvmStatic fun builder() = Builder() } @@ -140,7 +160,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(responses, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(responses, additionalProperties.toMutableMap()) } } @@ -154,7 +179,7 @@ private constructor( while (index < page.responses().size) { yield(page.responses()[index++]) } - page = page.getNextPage().orElse(null) ?: break + page = page.getNextPage().getOrNull() ?: break index = 0 } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyPageAsync.kt index 8693075d..8ac7b9d6 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyPageAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyPageAsync.kt @@ -10,15 +10,15 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.async.hris.IndividualServiceAsync +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull /** Read individual data, excluding income and employment data */ class HrisIndividualRetrieveManyPageAsync @@ -71,25 +71,33 @@ private constructor( ) = HrisIndividualRetrieveManyPageAsync(individualsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("responses") - private val responses: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val responses: JsonField>, + private val additionalProperties: MutableMap, ) { - fun responses(): List = responses.getNullable("responses") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("responses") + responses: JsonField> = JsonMissing.of() + ) : this(responses, mutableMapOf()) + + fun responses(): List = + responses.getOptional("responses").getOrNull() ?: listOf() @JsonProperty("responses") fun _responses(): Optional>> = Optional.ofNullable(responses) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -102,6 +110,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -119,6 +135,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisIndividualRetrieveManyPageAsync]. + */ @JvmStatic fun builder() = Builder() } @@ -143,7 +163,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(responses, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(responses, additionalProperties.toMutableMap()) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyParams.kt index 3809d289..6a0cedfb 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyParams.kt @@ -10,14 +10,16 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Read individual data, excluding income and employment data */ class HrisIndividualRetrieveManyParams @@ -27,12 +29,30 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun options(): Optional = body.options() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun requests(): Optional> = body.requests() + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ fun _options(): JsonField = body._options() + /** + * Returns the raw JSON value of [requests]. + * + * Unlike [requests], this method doesn't throw if the JSON field has an unexpected type. + */ fun _requests(): JsonField> = body._requests() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -41,155 +61,20 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("options") - @ExcludeMissing - private val options: JsonField = JsonMissing.of(), - @JsonProperty("requests") - @ExcludeMissing - private val requests: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun options(): Optional = Optional.ofNullable(options.getNullable("options")) - - fun requests(): Optional> = - Optional.ofNullable(requests.getNullable("requests")) - - @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = options - - @JsonProperty("requests") - @ExcludeMissing - fun _requests(): JsonField> = requests - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - options().ifPresent { it.validate() } - requests().ifPresent { it.forEach { it.validate() } } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var options: JsonField = JsonMissing.of() - private var requests: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - options = body.options - requests = body.requests.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - fun options(options: Options?) = options(JsonField.ofNullable(options)) - - fun options(options: Optional) = options(options.orElse(null)) - - fun options(options: JsonField) = apply { this.options = options } - - fun requests(requests: List) = requests(JsonField.of(requests)) - - fun requests(requests: JsonField>) = apply { - this.requests = requests.map { it.toMutableList() } - } - - fun addRequest(request: Request) = apply { - requests = - (requests ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(request) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = - Body( - options, - (requests ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && options == other.options && requests == other.requests && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(options, requests, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{options=$options, requests=$requests, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): HrisIndividualRetrieveManyParams = builder().build() + /** + * Returns a mutable builder for constructing an instance of + * [HrisIndividualRetrieveManyParams]. + */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisIndividualRetrieveManyParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -205,16 +90,45 @@ private constructor( hrisIndividualRetrieveManyParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [options] + * - [requests] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + fun options(options: Options?) = apply { body.options(options) } - fun options(options: Optional) = options(options.orElse(null)) + /** Alias for calling [Builder.options] with `options.orElse(null)`. */ + fun options(options: Optional) = options(options.getOrNull()) + /** + * Sets [Builder.options] to an arbitrary JSON value. + * + * You should usually call [Builder.options] with a well-typed [Options] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun options(options: JsonField) = apply { body.options(options) } fun requests(requests: List) = apply { body.requests(requests) } + /** + * Sets [Builder.requests] to an arbitrary JSON value. + * + * You should usually call [Builder.requests] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun requests(requests: JsonField>) = apply { body.requests(requests) } + /** + * Adds a single [Request] to [requests]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addRequest(request: Request) = apply { body.addRequest(request) } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { @@ -334,6 +248,11 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisIndividualRetrieveManyParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): HrisIndividualRetrieveManyParams = HrisIndividualRetrieveManyParams( body.build(), @@ -342,40 +261,248 @@ private constructor( ) } - @NoAutoDetect - class Options - @JsonCreator + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body private constructor( - @JsonProperty("include") - @ExcludeMissing - private val include: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val options: JsonField, + private val requests: JsonField>, + private val additionalProperties: MutableMap, ) { - fun include(): Optional> = Optional.ofNullable(include.getNullable("include")) + @JsonCreator + private constructor( + @JsonProperty("options") @ExcludeMissing options: JsonField = JsonMissing.of(), + @JsonProperty("requests") + @ExcludeMissing + requests: JsonField> = JsonMissing.of(), + ) : this(options, requests, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun options(): Optional = options.getOptional("options") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun requests(): Optional> = requests.getOptional("requests") + + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = options - @JsonProperty("include") @ExcludeMissing fun _include(): JsonField> = include + /** + * Returns the raw JSON value of [requests]. + * + * Unlike [requests], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("requests") + @ExcludeMissing + fun _requests(): JsonField> = requests + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var options: JsonField = JsonMissing.of() + private var requests: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + options = body.options + requests = body.requests.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + fun options(options: Options?) = options(JsonField.ofNullable(options)) + + /** Alias for calling [Builder.options] with `options.orElse(null)`. */ + fun options(options: Optional) = options(options.getOrNull()) + + /** + * Sets [Builder.options] to an arbitrary JSON value. + * + * You should usually call [Builder.options] with a well-typed [Options] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun options(options: JsonField) = apply { this.options = options } + + fun requests(requests: List) = requests(JsonField.of(requests)) + + /** + * Sets [Builder.requests] to an arbitrary JSON value. + * + * You should usually call [Builder.requests] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun requests(requests: JsonField>) = apply { + this.requests = requests.map { it.toMutableList() } + } + + /** + * Adds a single [Request] to [requests]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addRequest(request: Request) = apply { + requests = + (requests ?: JsonField.of(mutableListOf())).also { + checkKnown("requests", it).add(request) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body( + options, + (requests ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } private var validated: Boolean = false - fun validate(): Options = apply { + fun validate(): Body = apply { if (validated) { return@apply } - include() + options().ifPresent { it.validate() } + requests().ifPresent { it.forEach { it.validate() } } validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (options.asKnown().getOrNull()?.validity() ?: 0) + + (requests.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && options == other.options && requests == other.requests && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(options, requests, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{options=$options, requests=$requests, additionalProperties=$additionalProperties}" + } + + class Options + private constructor( + private val include: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("include") + @ExcludeMissing + include: JsonField> = JsonMissing.of() + ) : this(include, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun include(): Optional> = include.getOptional("include") + + /** + * Returns the raw JSON value of [include]. + * + * Unlike [include], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("include") @ExcludeMissing fun _include(): JsonField> = include + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Options]. */ @JvmStatic fun builder() = Builder() } @@ -393,20 +520,26 @@ private constructor( fun include(include: List) = include(JsonField.of(include)) + /** + * Sets [Builder.include] to an arbitrary JSON value. + * + * You should usually call [Builder.include] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun include(include: JsonField>) = apply { this.include = include.map { it.toMutableList() } } + /** + * Adds a single [String] to [Builder.include]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addInclude(include: String) = apply { this.include = - (this.include ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(include) + (this.include ?: JsonField.of(mutableListOf())).also { + checkKnown("include", it).add(include) } } @@ -429,13 +562,45 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Options]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Options = Options( (include ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Options = apply { + if (validated) { + return@apply + } + + include() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (include.asKnown().getOrNull()?.size ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -454,43 +619,50 @@ private constructor( "Options{include=$include, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Request - @JsonCreator private constructor( - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val individualId: JsonField, + private val additionalProperties: MutableMap, ) { - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) - + @JsonCreator + private constructor( + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of() + ) : this(individualId, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") + + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Request = apply { - if (validated) { - return@apply - } - - individualId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Request]. */ @JvmStatic fun builder() = Builder() } @@ -508,6 +680,13 @@ private constructor( fun individualId(individualId: String) = individualId(JsonField.of(individualId)) + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -531,9 +710,42 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Request = Request(individualId, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Request]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Request = Request(individualId, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Request = apply { + if (validated) { + return@apply + } + + individualId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (individualId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyPage.kt index 6e8a850e..865968a0 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyPage.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyPage.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.blocking.hris.PayStatementService +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull /** * Read detailed pay statements for each individual. @@ -72,25 +72,33 @@ private constructor( ) = HrisPayStatementRetrieveManyPage(payStatementsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("responses") - private val responses: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val responses: JsonField>, + private val additionalProperties: MutableMap, ) { - fun responses(): List = responses.getNullable("responses") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("responses") + responses: JsonField> = JsonMissing.of() + ) : this(responses, mutableMapOf()) + + fun responses(): List = + responses.getOptional("responses").getOrNull() ?: listOf() @JsonProperty("responses") fun _responses(): Optional>> = Optional.ofNullable(responses) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -103,6 +111,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -120,6 +136,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisPayStatementRetrieveManyPage]. + */ @JvmStatic fun builder() = Builder() } @@ -145,7 +165,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(responses, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(responses, additionalProperties.toMutableMap()) } } @@ -159,7 +184,7 @@ private constructor( while (index < page.responses().size) { yield(page.responses()[index++]) } - page = page.getNextPage().orElse(null) ?: break + page = page.getNextPage().getOrNull() ?: break index = 0 } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyPageAsync.kt index e1e84e39..8ec74337 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyPageAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyPageAsync.kt @@ -10,15 +10,15 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.async.hris.PayStatementServiceAsync +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull /** * Read detailed pay statements for each individual. @@ -75,25 +75,33 @@ private constructor( ) = HrisPayStatementRetrieveManyPageAsync(payStatementsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("responses") - private val responses: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val responses: JsonField>, + private val additionalProperties: MutableMap, ) { - fun responses(): List = responses.getNullable("responses") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("responses") + responses: JsonField> = JsonMissing.of() + ) : this(responses, mutableMapOf()) + + fun responses(): List = + responses.getOptional("responses").getOrNull() ?: listOf() @JsonProperty("responses") fun _responses(): Optional>> = Optional.ofNullable(responses) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -106,6 +114,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -123,6 +139,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisPayStatementRetrieveManyPageAsync]. + */ @JvmStatic fun builder() = Builder() } @@ -148,7 +168,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(responses, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(responses, additionalProperties.toMutableMap()) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyParams.kt index 7bf49d28..62779262 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyParams.kt @@ -10,15 +10,17 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** * Read detailed pay statements for each individual. @@ -32,10 +34,19 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { - /** The array of batch requests. */ + /** + * The array of batch requests. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun requests(): List = body.requests() - /** The array of batch requests. */ + /** + * Returns the raw JSON value of [requests]. + * + * Unlike [requests], this method doesn't throw if the JSON field has an unexpected type. + */ fun _requests(): JsonField> = body._requests() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -44,140 +55,23 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("requests") - @ExcludeMissing - private val requests: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** The array of batch requests. */ - fun requests(): List = requests.getRequired("requests") - - /** The array of batch requests. */ - @JsonProperty("requests") - @ExcludeMissing - fun _requests(): JsonField> = requests - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - requests().forEach { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var requests: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - requests = body.requests.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** The array of batch requests. */ - fun requests(requests: List) = requests(JsonField.of(requests)) - - /** The array of batch requests. */ - fun requests(requests: JsonField>) = apply { - this.requests = requests.map { it.toMutableList() } - } - - /** The array of batch requests. */ - fun addRequest(request: Request) = apply { - requests = - (requests ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(request) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = - Body( - checkRequired("requests", requests).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && requests == other.requests && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(requests, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{requests=$requests, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [HrisPayStatementRetrieveManyParams]. + * + * The following fields are required: + * ```java + * .requests() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisPayStatementRetrieveManyParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -193,13 +87,32 @@ private constructor( hrisPayStatementRetrieveManyParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [requests] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** The array of batch requests. */ fun requests(requests: List) = apply { body.requests(requests) } - /** The array of batch requests. */ + /** + * Sets [Builder.requests] to an arbitrary JSON value. + * + * You should usually call [Builder.requests] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun requests(requests: JsonField>) = apply { body.requests(requests) } - /** The array of batch requests. */ + /** + * Adds a single [Request] to [requests]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addRequest(request: Request) = apply { body.addRequest(request) } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { @@ -319,6 +232,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisPayStatementRetrieveManyParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .requests() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): HrisPayStatementRetrieveManyParams = HrisPayStatementRetrieveManyParams( body.build(), @@ -327,62 +252,274 @@ private constructor( ) } - @NoAutoDetect - class Request - @JsonCreator + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body private constructor( - @JsonProperty("payment_id") - @ExcludeMissing - private val paymentId: JsonField = JsonMissing.of(), - @JsonProperty("limit") - @ExcludeMissing - private val limit: JsonField = JsonMissing.of(), - @JsonProperty("offset") + private val requests: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("requests") + @ExcludeMissing + requests: JsonField> = JsonMissing.of() + ) : this(requests, mutableMapOf()) + + /** + * The array of batch requests. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun requests(): List = requests.getRequired("requests") + + /** + * Returns the raw JSON value of [requests]. + * + * Unlike [requests], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("requests") @ExcludeMissing - private val offset: JsonField = JsonMissing.of(), + fun _requests(): JsonField> = requests + @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } - /** A stable Finch `id` (UUID v4) for a payment. */ - fun paymentId(): String = paymentId.getRequired("payment_id") + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - /** Number of pay statements to return (defaults to all). */ - fun limit(): Optional = Optional.ofNullable(limit.getNullable("limit")) + fun toBuilder() = Builder().from(this) - /** Index to start from. */ - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) + companion object { - /** A stable Finch `id` (UUID v4) for a payment. */ - @JsonProperty("payment_id") @ExcludeMissing fun _paymentId(): JsonField = paymentId + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .requests() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - /** Number of pay statements to return (defaults to all). */ - @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit + /** A builder for [Body]. */ + class Builder internal constructor() { - /** Index to start from. */ - @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + private var requests: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + @JvmSynthetic + internal fun from(body: Body) = apply { + requests = body.requests.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The array of batch requests. */ + fun requests(requests: List) = requests(JsonField.of(requests)) + + /** + * Sets [Builder.requests] to an arbitrary JSON value. + * + * You should usually call [Builder.requests] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun requests(requests: JsonField>) = apply { + this.requests = requests.map { it.toMutableList() } + } + + /** + * Adds a single [Request] to [requests]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addRequest(request: Request) = apply { + requests = + (requests ?: JsonField.of(mutableListOf())).also { + checkKnown("requests", it).add(request) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .requests() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("requests", requests).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } private var validated: Boolean = false - fun validate(): Request = apply { + fun validate(): Body = apply { if (validated) { return@apply } - paymentId() - limit() - offset() + requests().forEach { it.validate() } validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (requests.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && requests == other.requests && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(requests, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{requests=$requests, additionalProperties=$additionalProperties}" + } + + class Request + private constructor( + private val paymentId: JsonField, + private val limit: JsonField, + private val offset: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("payment_id") + @ExcludeMissing + paymentId: JsonField = JsonMissing.of(), + @JsonProperty("limit") @ExcludeMissing limit: JsonField = JsonMissing.of(), + @JsonProperty("offset") @ExcludeMissing offset: JsonField = JsonMissing.of(), + ) : this(paymentId, limit, offset, mutableMapOf()) + + /** + * A stable Finch `id` (UUID v4) for a payment. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun paymentId(): String = paymentId.getRequired("payment_id") + + /** + * Number of pay statements to return (defaults to all). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun limit(): Optional = limit.getOptional("limit") + + /** + * Index to start from. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun offset(): Optional = offset.getOptional("offset") + + /** + * Returns the raw JSON value of [paymentId]. + * + * Unlike [paymentId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("payment_id") @ExcludeMissing fun _paymentId(): JsonField = paymentId + + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit + + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Request]. + * + * The following fields are required: + * ```java + * .paymentId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -405,19 +542,37 @@ private constructor( /** A stable Finch `id` (UUID v4) for a payment. */ fun paymentId(paymentId: String) = paymentId(JsonField.of(paymentId)) - /** A stable Finch `id` (UUID v4) for a payment. */ + /** + * Sets [Builder.paymentId] to an arbitrary JSON value. + * + * You should usually call [Builder.paymentId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun paymentId(paymentId: JsonField) = apply { this.paymentId = paymentId } /** Number of pay statements to return (defaults to all). */ fun limit(limit: Long) = limit(JsonField.of(limit)) - /** Number of pay statements to return (defaults to all). */ + /** + * Sets [Builder.limit] to an arbitrary JSON value. + * + * You should usually call [Builder.limit] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun limit(limit: JsonField) = apply { this.limit = limit } /** Index to start from. */ fun offset(offset: Long) = offset(JsonField.of(offset)) - /** Index to start from. */ + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun offset(offset: JsonField) = apply { this.offset = offset } fun additionalProperties(additionalProperties: Map) = apply { @@ -439,15 +594,60 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Request]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .paymentId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Request = Request( checkRequired("paymentId", paymentId), limit, offset, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Request = apply { + if (validated) { + return@apply + } + + paymentId() + limit() + offset() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (paymentId.asKnown().isPresent) 1 else 0) + + (if (limit.asKnown().isPresent) 1 else 0) + + (if (offset.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPaymentListPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPaymentListPage.kt index c321b38f..ba026277 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPaymentListPage.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPaymentListPage.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.blocking.hris.PaymentService +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull /** Read payroll and contractor related payments by the company. */ class HrisPaymentListPage @@ -65,23 +65,30 @@ private constructor( HrisPaymentListPage(paymentsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -94,6 +101,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -111,6 +126,7 @@ private constructor( companion object { + /** Returns a mutable builder for constructing an instance of [HrisPaymentListPage]. */ @JvmStatic fun builder() = Builder() } @@ -133,7 +149,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } @@ -146,7 +167,7 @@ private constructor( while (index < page.items().size) { yield(page.items()[index++]) } - page = page.getNextPage().orElse(null) ?: break + page = page.getNextPage().getOrNull() ?: break index = 0 } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPaymentListPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPaymentListPageAsync.kt index c2d3ad50..c4f2c62f 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPaymentListPageAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPaymentListPageAsync.kt @@ -10,15 +10,15 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.async.hris.PaymentServiceAsync +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull /** Read payroll and contractor related payments by the company. */ class HrisPaymentListPageAsync @@ -71,23 +71,30 @@ private constructor( ) = HrisPaymentListPageAsync(paymentsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -100,6 +107,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -117,6 +132,9 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of [HrisPaymentListPageAsync]. + */ @JvmStatic fun builder() = Builder() } @@ -139,7 +157,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPaymentListParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPaymentListParams.kt index f0dc741f..918a4ba6 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPaymentListParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/HrisPaymentListParams.kt @@ -2,7 +2,6 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers @@ -29,25 +28,23 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.endDate.let { queryParams.put("end_date", listOf(it.toString())) } - this.startDate.let { queryParams.put("start_date", listOf(it.toString())) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [HrisPaymentListParams]. + * + * The following fields are required: + * ```java + * .endDate() + * .startDate() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [HrisPaymentListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var endDate: LocalDate? = null @@ -167,6 +164,19 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [HrisPaymentListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .endDate() + * .startDate() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): HrisPaymentListParams = HrisPaymentListParams( checkRequired("endDate", endDate), @@ -176,6 +186,17 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + put("end_date", endDate.toString()) + put("start_date", startDate.toString()) + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Income.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Income.kt index b0cf2130..03ac872e 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Income.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Income.kt @@ -11,88 +11,114 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** * The employee's income as reported by the provider. This may not always be annualized income, but * may be in units of bi-weekly, semi-monthly, daily, etc, depending on what information the * provider returns. */ -@NoAutoDetect class Income -@JsonCreator private constructor( - @JsonProperty("amount") @ExcludeMissing private val amount: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("effective_date") - @ExcludeMissing - private val effectiveDate: JsonField = JsonMissing.of(), - @JsonProperty("unit") @ExcludeMissing private val unit: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val amount: JsonField, + private val currency: JsonField, + private val effectiveDate: JsonField, + private val unit: JsonField, + private val additionalProperties: MutableMap, ) { - /** The income amount in cents. */ - fun amount(): Optional = Optional.ofNullable(amount.getNullable("amount")) + @JsonCreator + private constructor( + @JsonProperty("amount") @ExcludeMissing amount: JsonField = JsonMissing.of(), + @JsonProperty("currency") @ExcludeMissing currency: JsonField = JsonMissing.of(), + @JsonProperty("effective_date") + @ExcludeMissing + effectiveDate: JsonField = JsonMissing.of(), + @JsonProperty("unit") @ExcludeMissing unit: JsonField = JsonMissing.of(), + ) : this(amount, currency, effectiveDate, unit, mutableMapOf()) + + /** + * The income amount in cents. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") - /** The currency code. */ - fun currency(): Optional = Optional.ofNullable(currency.getNullable("currency")) + /** + * The currency code. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") - /** The date the income amount went into effect. */ - fun effectiveDate(): Optional = - Optional.ofNullable(effectiveDate.getNullable("effective_date")) + /** + * The date the income amount went into effect. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun effectiveDate(): Optional = effectiveDate.getOptional("effective_date") /** * The income unit of payment. Options: `yearly`, `quarterly`, `monthly`, `semi_monthly`, * `bi_weekly`, `weekly`, `daily`, `hourly`, and `fixed`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun unit(): Optional = Optional.ofNullable(unit.getNullable("unit")) + fun unit(): Optional = unit.getOptional("unit") - /** The income amount in cents. */ + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount - /** The currency code. */ + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency - /** The date the income amount went into effect. */ + /** + * Returns the raw JSON value of [effectiveDate]. + * + * Unlike [effectiveDate], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("effective_date") @ExcludeMissing fun _effectiveDate(): JsonField = effectiveDate /** - * The income unit of payment. Options: `yearly`, `quarterly`, `monthly`, `semi_monthly`, - * `bi_weekly`, `weekly`, `daily`, `hourly`, and `fixed`. + * Returns the raw JSON value of [unit]. + * + * Unlike [unit], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("unit") @ExcludeMissing fun _unit(): JsonField = unit + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Income = apply { - if (validated) { - return@apply - } - - amount() - currency() - effectiveDate() - unit() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Income]. */ @JvmStatic fun builder() = Builder() } @@ -117,34 +143,53 @@ private constructor( /** The income amount in cents. */ fun amount(amount: Long?) = amount(JsonField.ofNullable(amount)) - /** The income amount in cents. */ + /** + * Alias for [Builder.amount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun amount(amount: Long) = amount(amount as Long?) - /** The income amount in cents. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun amount(amount: Optional) = amount(amount.orElse(null) as Long?) + /** Alias for calling [Builder.amount] with `amount.orElse(null)`. */ + fun amount(amount: Optional) = amount(amount.getOrNull()) - /** The income amount in cents. */ + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } /** The currency code. */ fun currency(currency: String?) = currency(JsonField.ofNullable(currency)) - /** The currency code. */ - fun currency(currency: Optional) = currency(currency.orElse(null)) + /** Alias for calling [Builder.currency] with `currency.orElse(null)`. */ + fun currency(currency: Optional) = currency(currency.getOrNull()) - /** The currency code. */ + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } /** The date the income amount went into effect. */ fun effectiveDate(effectiveDate: String?) = effectiveDate(JsonField.ofNullable(effectiveDate)) - /** The date the income amount went into effect. */ + /** Alias for calling [Builder.effectiveDate] with `effectiveDate.orElse(null)`. */ fun effectiveDate(effectiveDate: Optional) = - effectiveDate(effectiveDate.orElse(null)) + effectiveDate(effectiveDate.getOrNull()) - /** The date the income amount went into effect. */ + /** + * Sets [Builder.effectiveDate] to an arbitrary JSON value. + * + * You should usually call [Builder.effectiveDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun effectiveDate(effectiveDate: JsonField) = apply { this.effectiveDate = effectiveDate } @@ -155,15 +200,14 @@ private constructor( */ fun unit(unit: Unit?) = unit(JsonField.ofNullable(unit)) - /** - * The income unit of payment. Options: `yearly`, `quarterly`, `monthly`, `semi_monthly`, - * `bi_weekly`, `weekly`, `daily`, `hourly`, and `fixed`. - */ - fun unit(unit: Optional) = unit(unit.orElse(null)) + /** Alias for calling [Builder.unit] with `unit.orElse(null)`. */ + fun unit(unit: Optional) = unit(unit.getOrNull()) /** - * The income unit of payment. Options: `yearly`, `quarterly`, `monthly`, `semi_monthly`, - * `bi_weekly`, `weekly`, `daily`, `hourly`, and `fixed`. + * Sets [Builder.unit] to an arbitrary JSON value. + * + * You should usually call [Builder.unit] with a well-typed [Unit] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun unit(unit: JsonField) = apply { this.unit = unit } @@ -186,10 +230,49 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Income]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Income = - Income(amount, currency, effectiveDate, unit, additionalProperties.toImmutable()) + Income(amount, currency, effectiveDate, unit, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Income = apply { + if (validated) { + return@apply + } + + amount() + currency() + effectiveDate() + unit().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (effectiveDate.asKnown().isPresent) 1 else 0) + + (unit.asKnown().getOrNull()?.validity() ?: 0) + /** * The income unit of payment. Options: `yearly`, `quarterly`, `monthly`, `semi_monthly`, * `bi_weekly`, `weekly`, `daily`, `hourly`, and `fixed`. @@ -320,6 +403,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Unit = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Individual.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Individual.kt index e2f8fcb0..bffd234c 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Individual.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Individual.kt @@ -11,179 +11,288 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class Individual -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("dob") @ExcludeMissing private val dob: JsonField = JsonMissing.of(), - @JsonProperty("emails") - @ExcludeMissing - private val emails: JsonField> = JsonMissing.of(), - @JsonProperty("encrypted_ssn") - @ExcludeMissing - private val encryptedSsn: JsonField = JsonMissing.of(), - @JsonProperty("ethnicity") - @ExcludeMissing - private val ethnicity: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("gender") - @ExcludeMissing - private val gender: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), - @JsonProperty("phone_numbers") - @ExcludeMissing - private val phoneNumbers: JsonField> = JsonMissing.of(), - @JsonProperty("preferred_name") - @ExcludeMissing - private val preferredName: JsonField = JsonMissing.of(), - @JsonProperty("residence") - @ExcludeMissing - private val residence: JsonField = JsonMissing.of(), - @JsonProperty("ssn") @ExcludeMissing private val ssn: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val dob: JsonField, + private val emails: JsonField>, + private val encryptedSsn: JsonField, + private val ethnicity: JsonField, + private val firstName: JsonField, + private val gender: JsonField, + private val lastName: JsonField, + private val middleName: JsonField, + private val phoneNumbers: JsonField>, + private val preferredName: JsonField, + private val residence: JsonField, + private val ssn: JsonField, + private val additionalProperties: MutableMap, ) { - /** A stable Finch `id` (UUID v4) for an individual in the company. */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("dob") @ExcludeMissing dob: JsonField = JsonMissing.of(), + @JsonProperty("emails") @ExcludeMissing emails: JsonField> = JsonMissing.of(), + @JsonProperty("encrypted_ssn") + @ExcludeMissing + encryptedSsn: JsonField = JsonMissing.of(), + @JsonProperty("ethnicity") + @ExcludeMissing + ethnicity: JsonField = JsonMissing.of(), + @JsonProperty("first_name") @ExcludeMissing firstName: JsonField = JsonMissing.of(), + @JsonProperty("gender") @ExcludeMissing gender: JsonField = JsonMissing.of(), + @JsonProperty("last_name") @ExcludeMissing lastName: JsonField = JsonMissing.of(), + @JsonProperty("middle_name") + @ExcludeMissing + middleName: JsonField = JsonMissing.of(), + @JsonProperty("phone_numbers") + @ExcludeMissing + phoneNumbers: JsonField> = JsonMissing.of(), + @JsonProperty("preferred_name") + @ExcludeMissing + preferredName: JsonField = JsonMissing.of(), + @JsonProperty("residence") + @ExcludeMissing + residence: JsonField = JsonMissing.of(), + @JsonProperty("ssn") @ExcludeMissing ssn: JsonField = JsonMissing.of(), + ) : this( + id, + dob, + emails, + encryptedSsn, + ethnicity, + firstName, + gender, + lastName, + middleName, + phoneNumbers, + preferredName, + residence, + ssn, + mutableMapOf(), + ) + + /** + * A stable Finch `id` (UUID v4) for an individual in the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") - fun dob(): Optional = Optional.ofNullable(dob.getNullable("dob")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun dob(): Optional = dob.getOptional("dob") - fun emails(): Optional> = Optional.ofNullable(emails.getNullable("emails")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun emails(): Optional> = emails.getOptional("emails") /** * Social Security Number of the individual in **encrypted** format. This field is only * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set in * the body. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun encryptedSsn(): Optional = - Optional.ofNullable(encryptedSsn.getNullable("encrypted_ssn")) + fun encryptedSsn(): Optional = encryptedSsn.getOptional("encrypted_ssn") - /** The EEOC-defined ethnicity of the individual. */ - fun ethnicity(): Optional = Optional.ofNullable(ethnicity.getNullable("ethnicity")) + /** + * The EEOC-defined ethnicity of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun ethnicity(): Optional = ethnicity.getOptional("ethnicity") - /** The legal first name of the individual. */ - fun firstName(): Optional = Optional.ofNullable(firstName.getNullable("first_name")) + /** + * The legal first name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") - /** The gender of the individual. */ - fun gender(): Optional = Optional.ofNullable(gender.getNullable("gender")) + /** + * The gender of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun gender(): Optional = gender.getOptional("gender") - /** The legal last name of the individual. */ - fun lastName(): Optional = Optional.ofNullable(lastName.getNullable("last_name")) + /** + * The legal last name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") - /** The legal middle name of the individual. */ - fun middleName(): Optional = Optional.ofNullable(middleName.getNullable("middle_name")) + /** + * The legal middle name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") - fun phoneNumbers(): Optional> = - Optional.ofNullable(phoneNumbers.getNullable("phone_numbers")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun phoneNumbers(): Optional> = phoneNumbers.getOptional("phone_numbers") - /** The preferred name of the individual. */ - fun preferredName(): Optional = - Optional.ofNullable(preferredName.getNullable("preferred_name")) + /** + * The preferred name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun preferredName(): Optional = preferredName.getOptional("preferred_name") - fun residence(): Optional = Optional.ofNullable(residence.getNullable("residence")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun residence(): Optional = residence.getOptional("residence") /** * Social Security Number of the individual. This field is only available with the `ssn` scope * enabled and the `options: { include: ['ssn'] }` param set in the body. * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun ssn(): Optional = Optional.ofNullable(ssn.getNullable("ssn")) + fun ssn(): Optional = ssn.getOptional("ssn") - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [dob]. + * + * Unlike [dob], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("dob") @ExcludeMissing fun _dob(): JsonField = dob + /** + * Returns the raw JSON value of [emails]. + * + * Unlike [emails], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("emails") @ExcludeMissing fun _emails(): JsonField> = emails /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set in - * the body. + * Returns the raw JSON value of [encryptedSsn]. + * + * Unlike [encryptedSsn], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("encrypted_ssn") @ExcludeMissing fun _encryptedSsn(): JsonField = encryptedSsn - /** The EEOC-defined ethnicity of the individual. */ + /** + * Returns the raw JSON value of [ethnicity]. + * + * Unlike [ethnicity], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("ethnicity") @ExcludeMissing fun _ethnicity(): JsonField = ethnicity - /** The legal first name of the individual. */ + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName - /** The gender of the individual. */ + /** + * Returns the raw JSON value of [gender]. + * + * Unlike [gender], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("gender") @ExcludeMissing fun _gender(): JsonField = gender - /** The legal last name of the individual. */ + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName - /** The legal middle name of the individual. */ + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("middle_name") @ExcludeMissing fun _middleName(): JsonField = middleName + /** + * Returns the raw JSON value of [phoneNumbers]. + * + * Unlike [phoneNumbers], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("phone_numbers") @ExcludeMissing fun _phoneNumbers(): JsonField> = phoneNumbers - /** The preferred name of the individual. */ + /** + * Returns the raw JSON value of [preferredName]. + * + * Unlike [preferredName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("preferred_name") @ExcludeMissing fun _preferredName(): JsonField = preferredName + /** + * Returns the raw JSON value of [residence]. + * + * Unlike [residence], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("residence") @ExcludeMissing fun _residence(): JsonField = residence /** - * Social Security Number of the individual. This field is only available with the `ssn` scope - * enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). + * Returns the raw JSON value of [ssn]. + * + * Unlike [ssn], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("ssn") @ExcludeMissing fun _ssn(): JsonField = ssn + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Individual = apply { - if (validated) { - return@apply - } - - id() - dob() - emails().ifPresent { it.forEach { it.validate() } } - encryptedSsn() - ethnicity() - firstName() - gender() - lastName() - middleName() - phoneNumbers().ifPresent { it.forEach { it?.validate() } } - preferredName() - residence().ifPresent { it.validate() } - ssn() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Individual]. */ @JvmStatic fun builder() = Builder() } @@ -226,33 +335,52 @@ private constructor( /** A stable Finch `id` (UUID v4) for an individual in the company. */ fun id(id: String) = id(JsonField.of(id)) - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun dob(dob: String?) = dob(JsonField.ofNullable(dob)) - fun dob(dob: Optional) = dob(dob.orElse(null)) + /** Alias for calling [Builder.dob] with `dob.orElse(null)`. */ + fun dob(dob: Optional) = dob(dob.getOrNull()) + /** + * Sets [Builder.dob] to an arbitrary JSON value. + * + * You should usually call [Builder.dob] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun dob(dob: JsonField) = apply { this.dob = dob } fun emails(emails: List?) = emails(JsonField.ofNullable(emails)) - fun emails(emails: Optional>) = emails(emails.orElse(null)) + /** Alias for calling [Builder.emails] with `emails.orElse(null)`. */ + fun emails(emails: Optional>) = emails(emails.getOrNull()) + /** + * Sets [Builder.emails] to an arbitrary JSON value. + * + * You should usually call [Builder.emails] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun emails(emails: JsonField>) = apply { this.emails = emails.map { it.toMutableList() } } + /** + * Adds a single [Email] to [emails]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addEmail(email: Email) = apply { emails = - (emails ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(email) + (emails ?: JsonField.of(mutableListOf())).also { + checkKnown("emails", it).add(email) } } @@ -263,17 +391,15 @@ private constructor( */ fun encryptedSsn(encryptedSsn: String?) = encryptedSsn(JsonField.ofNullable(encryptedSsn)) - /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set - * in the body. - */ - fun encryptedSsn(encryptedSsn: Optional) = encryptedSsn(encryptedSsn.orElse(null)) + /** Alias for calling [Builder.encryptedSsn] with `encryptedSsn.orElse(null)`. */ + fun encryptedSsn(encryptedSsn: Optional) = encryptedSsn(encryptedSsn.getOrNull()) /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set - * in the body. + * Sets [Builder.encryptedSsn] to an arbitrary JSON value. + * + * You should usually call [Builder.encryptedSsn] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ fun encryptedSsn(encryptedSsn: JsonField) = apply { this.encryptedSsn = encryptedSsn @@ -282,68 +408,103 @@ private constructor( /** The EEOC-defined ethnicity of the individual. */ fun ethnicity(ethnicity: Ethnicity?) = ethnicity(JsonField.ofNullable(ethnicity)) - /** The EEOC-defined ethnicity of the individual. */ - fun ethnicity(ethnicity: Optional) = ethnicity(ethnicity.orElse(null)) + /** Alias for calling [Builder.ethnicity] with `ethnicity.orElse(null)`. */ + fun ethnicity(ethnicity: Optional) = ethnicity(ethnicity.getOrNull()) - /** The EEOC-defined ethnicity of the individual. */ + /** + * Sets [Builder.ethnicity] to an arbitrary JSON value. + * + * You should usually call [Builder.ethnicity] with a well-typed [Ethnicity] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun ethnicity(ethnicity: JsonField) = apply { this.ethnicity = ethnicity } /** The legal first name of the individual. */ fun firstName(firstName: String?) = firstName(JsonField.ofNullable(firstName)) - /** The legal first name of the individual. */ - fun firstName(firstName: Optional) = firstName(firstName.orElse(null)) + /** Alias for calling [Builder.firstName] with `firstName.orElse(null)`. */ + fun firstName(firstName: Optional) = firstName(firstName.getOrNull()) - /** The legal first name of the individual. */ + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun firstName(firstName: JsonField) = apply { this.firstName = firstName } /** The gender of the individual. */ fun gender(gender: Gender?) = gender(JsonField.ofNullable(gender)) - /** The gender of the individual. */ - fun gender(gender: Optional) = gender(gender.orElse(null)) + /** Alias for calling [Builder.gender] with `gender.orElse(null)`. */ + fun gender(gender: Optional) = gender(gender.getOrNull()) - /** The gender of the individual. */ + /** + * Sets [Builder.gender] to an arbitrary JSON value. + * + * You should usually call [Builder.gender] with a well-typed [Gender] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun gender(gender: JsonField) = apply { this.gender = gender } /** The legal last name of the individual. */ fun lastName(lastName: String?) = lastName(JsonField.ofNullable(lastName)) - /** The legal last name of the individual. */ - fun lastName(lastName: Optional) = lastName(lastName.orElse(null)) + /** Alias for calling [Builder.lastName] with `lastName.orElse(null)`. */ + fun lastName(lastName: Optional) = lastName(lastName.getOrNull()) - /** The legal last name of the individual. */ + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun lastName(lastName: JsonField) = apply { this.lastName = lastName } /** The legal middle name of the individual. */ fun middleName(middleName: String?) = middleName(JsonField.ofNullable(middleName)) - /** The legal middle name of the individual. */ - fun middleName(middleName: Optional) = middleName(middleName.orElse(null)) + /** Alias for calling [Builder.middleName] with `middleName.orElse(null)`. */ + fun middleName(middleName: Optional) = middleName(middleName.getOrNull()) - /** The legal middle name of the individual. */ + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun middleName(middleName: JsonField) = apply { this.middleName = middleName } fun phoneNumbers(phoneNumbers: List?) = phoneNumbers(JsonField.ofNullable(phoneNumbers)) + /** Alias for calling [Builder.phoneNumbers] with `phoneNumbers.orElse(null)`. */ fun phoneNumbers(phoneNumbers: Optional>) = - phoneNumbers(phoneNumbers.orElse(null)) + phoneNumbers(phoneNumbers.getOrNull()) + /** + * Sets [Builder.phoneNumbers] to an arbitrary JSON value. + * + * You should usually call [Builder.phoneNumbers] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun phoneNumbers(phoneNumbers: JsonField>) = apply { this.phoneNumbers = phoneNumbers.map { it.toMutableList() } } + /** + * Adds a single [PhoneNumber] to [phoneNumbers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addPhoneNumber(phoneNumber: PhoneNumber) = apply { phoneNumbers = - (phoneNumbers ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(phoneNumber) + (phoneNumbers ?: JsonField.of(mutableListOf())).also { + checkKnown("phoneNumbers", it).add(phoneNumber) } } @@ -351,19 +512,33 @@ private constructor( fun preferredName(preferredName: String?) = preferredName(JsonField.ofNullable(preferredName)) - /** The preferred name of the individual. */ + /** Alias for calling [Builder.preferredName] with `preferredName.orElse(null)`. */ fun preferredName(preferredName: Optional) = - preferredName(preferredName.orElse(null)) + preferredName(preferredName.getOrNull()) - /** The preferred name of the individual. */ + /** + * Sets [Builder.preferredName] to an arbitrary JSON value. + * + * You should usually call [Builder.preferredName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun preferredName(preferredName: JsonField) = apply { this.preferredName = preferredName } fun residence(residence: Location?) = residence(JsonField.ofNullable(residence)) - fun residence(residence: Optional) = residence(residence.orElse(null)) + /** Alias for calling [Builder.residence] with `residence.orElse(null)`. */ + fun residence(residence: Optional) = residence(residence.getOrNull()) + /** + * Sets [Builder.residence] to an arbitrary JSON value. + * + * You should usually call [Builder.residence] with a well-typed [Location] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun residence(residence: JsonField) = apply { this.residence = residence } /** @@ -373,17 +548,14 @@ private constructor( */ fun ssn(ssn: String?) = ssn(JsonField.ofNullable(ssn)) - /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). - */ - fun ssn(ssn: Optional) = ssn(ssn.orElse(null)) + /** Alias for calling [Builder.ssn] with `ssn.orElse(null)`. */ + fun ssn(ssn: Optional) = ssn(ssn.getOrNull()) /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). + * Sets [Builder.ssn] to an arbitrary JSON value. + * + * You should usually call [Builder.ssn] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun ssn(ssn: JsonField) = apply { this.ssn = ssn } @@ -406,6 +578,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Individual]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Individual = Individual( id, @@ -421,50 +598,116 @@ private constructor( preferredName, residence, ssn, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Individual = apply { + if (validated) { + return@apply + } + + id() + dob() + emails().ifPresent { it.forEach { it.validate() } } + encryptedSsn() + ethnicity().ifPresent { it.validate() } + firstName() + gender().ifPresent { it.validate() } + lastName() + middleName() + phoneNumbers().ifPresent { it.forEach { it?.validate() } } + preferredName() + residence().ifPresent { it.validate() } + ssn() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (dob.asKnown().isPresent) 1 else 0) + + (emails.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (encryptedSsn.asKnown().isPresent) 1 else 0) + + (ethnicity.asKnown().getOrNull()?.validity() ?: 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (gender.asKnown().getOrNull()?.validity() ?: 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + + (phoneNumbers.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (preferredName.asKnown().isPresent) 1 else 0) + + (residence.asKnown().getOrNull()?.validity() ?: 0) + + (if (ssn.asKnown().isPresent) 1 else 0) + class Email - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Email = apply { - if (validated) { - return@apply - } - - data() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Email]. */ @JvmStatic fun builder() = Builder() } @@ -484,12 +727,27 @@ private constructor( fun data(data: String) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun data(data: JsonField) = apply { this.data = data } fun type(type: Type?) = type(JsonField.ofNullable(type)) - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -511,9 +769,44 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Email = Email(data, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Email]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Email = Email(data, type, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Email = apply { + if (validated) { + return@apply + } + + data() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -601,6 +894,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -756,6 +1076,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Ethnicity = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -866,6 +1213,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Gender = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -879,46 +1253,60 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class PhoneNumber - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PhoneNumber = apply { - if (validated) { - return@apply - } - - data() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [PhoneNumber]. */ @JvmStatic fun builder() = Builder() } @@ -938,14 +1326,30 @@ private constructor( fun data(data: String?) = data(JsonField.ofNullable(data)) - fun data(data: Optional) = data(data.orElse(null)) + /** Alias for calling [Builder.data] with `data.orElse(null)`. */ + fun data(data: Optional) = data(data.getOrNull()) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun data(data: JsonField) = apply { this.data = data } fun type(type: Type?) = type(JsonField.ofNullable(type)) - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -967,9 +1371,44 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): PhoneNumber = PhoneNumber(data, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [PhoneNumber]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): PhoneNumber = PhoneNumber(data, type, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): PhoneNumber = apply { + if (validated) { + return@apply + } + + data() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -1057,6 +1496,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualBenefit.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualBenefit.kt index e760e125..c42a1109 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualBenefit.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualBenefit.kt @@ -11,61 +11,85 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class IndividualBenefit -@JsonCreator private constructor( - @JsonProperty("body") @ExcludeMissing private val body: JsonField = JsonMissing.of(), - @JsonProperty("code") @ExcludeMissing private val code: JsonField = JsonMissing.of(), - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val body: JsonField, + private val code: JsonField, + private val individualId: JsonField, + private val additionalProperties: MutableMap, ) { - fun body(): Optional = Optional.ofNullable(body.getNullable("body")) - - fun code(): Optional = Optional.ofNullable(code.getNullable("code")) - - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) - + @JsonCreator + private constructor( + @JsonProperty("body") @ExcludeMissing body: JsonField = JsonMissing.of(), + @JsonProperty("code") @ExcludeMissing code: JsonField = JsonMissing.of(), + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of(), + ) : this(body, code, individualId, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun body(): Optional = body.getOptional("body") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun code(): Optional = code.getOptional("code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") + + /** + * Returns the raw JSON value of [body]. + * + * Unlike [body], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("body") @ExcludeMissing fun _body(): JsonField = body + /** + * Returns the raw JSON value of [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): IndividualBenefit = apply { - if (validated) { - return@apply - } - - body().ifPresent { it.validate() } - code() - individualId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [IndividualBenefit]. */ @JvmStatic fun builder() = Builder() } @@ -87,14 +111,33 @@ private constructor( fun body(body: Body) = body(JsonField.of(body)) + /** + * Sets [Builder.body] to an arbitrary JSON value. + * + * You should usually call [Builder.body] with a well-typed [Body] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun body(body: JsonField) = apply { this.body = body } fun code(code: Long) = code(JsonField.of(code)) + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun code(code: JsonField) = apply { this.code = code } fun individualId(individualId: String) = individualId(JsonField.of(individualId)) + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -118,100 +161,185 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [IndividualBenefit]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): IndividualBenefit = - IndividualBenefit(body, code, individualId, additionalProperties.toImmutable()) + IndividualBenefit(body, code, individualId, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): IndividualBenefit = apply { + if (validated) { + return@apply + } + + body().ifPresent { it.validate() } + code() + individualId() + validated = true } - @NoAutoDetect + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (body.asKnown().getOrNull()?.validity() ?: 0) + + (if (code.asKnown().isPresent) 1 else 0) + + (if (individualId.asKnown().isPresent) 1 else 0) + class Body - @JsonCreator private constructor( - @JsonProperty("annual_maximum") - @ExcludeMissing - private val annualMaximum: JsonField = JsonMissing.of(), - @JsonProperty("catch_up") - @ExcludeMissing - private val catchUp: JsonField = JsonMissing.of(), - @JsonProperty("company_contribution") - @ExcludeMissing - private val companyContribution: JsonField = JsonMissing.of(), - @JsonProperty("employee_deduction") - @ExcludeMissing - private val employeeDeduction: JsonField = JsonMissing.of(), - @JsonProperty("hsa_contribution_limit") - @ExcludeMissing - private val hsaContributionLimit: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val annualMaximum: JsonField, + private val catchUp: JsonField, + private val companyContribution: JsonField, + private val employeeDeduction: JsonField, + private val hsaContributionLimit: JsonField, + private val additionalProperties: MutableMap, ) { - /** If the benefit supports annual maximum, the amount in cents for this individual. */ - fun annualMaximum(): Optional = - Optional.ofNullable(annualMaximum.getNullable("annual_maximum")) + @JsonCreator + private constructor( + @JsonProperty("annual_maximum") + @ExcludeMissing + annualMaximum: JsonField = JsonMissing.of(), + @JsonProperty("catch_up") + @ExcludeMissing + catchUp: JsonField = JsonMissing.of(), + @JsonProperty("company_contribution") + @ExcludeMissing + companyContribution: JsonField = JsonMissing.of(), + @JsonProperty("employee_deduction") + @ExcludeMissing + employeeDeduction: JsonField = JsonMissing.of(), + @JsonProperty("hsa_contribution_limit") + @ExcludeMissing + hsaContributionLimit: JsonField = JsonMissing.of(), + ) : this( + annualMaximum, + catchUp, + companyContribution, + employeeDeduction, + hsaContributionLimit, + mutableMapOf(), + ) + + /** + * If the benefit supports annual maximum, the amount in cents for this individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun annualMaximum(): Optional = annualMaximum.getOptional("annual_maximum") /** * If the benefit supports catch up (401k, 403b, etc.), whether catch up is enabled for this * individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun catchUp(): Optional = Optional.ofNullable(catchUp.getNullable("catch_up")) + fun catchUp(): Optional = catchUp.getOptional("catch_up") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun companyContribution(): Optional = - Optional.ofNullable(companyContribution.getNullable("company_contribution")) + companyContribution.getOptional("company_contribution") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun employeeDeduction(): Optional = - Optional.ofNullable(employeeDeduction.getNullable("employee_deduction")) + employeeDeduction.getOptional("employee_deduction") - /** Type for HSA contribution limit if the benefit is a HSA. */ + /** + * Type for HSA contribution limit if the benefit is a HSA. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun hsaContributionLimit(): Optional = - Optional.ofNullable(hsaContributionLimit.getNullable("hsa_contribution_limit")) + hsaContributionLimit.getOptional("hsa_contribution_limit") - /** If the benefit supports annual maximum, the amount in cents for this individual. */ + /** + * Returns the raw JSON value of [annualMaximum]. + * + * Unlike [annualMaximum], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("annual_maximum") @ExcludeMissing fun _annualMaximum(): JsonField = annualMaximum /** - * If the benefit supports catch up (401k, 403b, etc.), whether catch up is enabled for this - * individual. + * Returns the raw JSON value of [catchUp]. + * + * Unlike [catchUp], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("catch_up") @ExcludeMissing fun _catchUp(): JsonField = catchUp + /** + * Returns the raw JSON value of [companyContribution]. + * + * Unlike [companyContribution], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("company_contribution") @ExcludeMissing fun _companyContribution(): JsonField = companyContribution + /** + * Returns the raw JSON value of [employeeDeduction]. + * + * Unlike [employeeDeduction], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("employee_deduction") @ExcludeMissing fun _employeeDeduction(): JsonField = employeeDeduction - /** Type for HSA contribution limit if the benefit is a HSA. */ + /** + * Returns the raw JSON value of [hsaContributionLimit]. + * + * Unlike [hsaContributionLimit], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("hsa_contribution_limit") @ExcludeMissing fun _hsaContributionLimit(): JsonField = hsaContributionLimit + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - annualMaximum() - catchUp() - companyContribution().ifPresent { it.validate() } - employeeDeduction().ifPresent { it.validate() } - hsaContributionLimit() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Body]. */ @JvmStatic fun builder() = Builder() } @@ -239,15 +367,24 @@ private constructor( fun annualMaximum(annualMaximum: Long?) = annualMaximum(JsonField.ofNullable(annualMaximum)) - /** If the benefit supports annual maximum, the amount in cents for this individual. */ + /** + * Alias for [Builder.annualMaximum]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun annualMaximum(annualMaximum: Long) = annualMaximum(annualMaximum as Long?) - /** If the benefit supports annual maximum, the amount in cents for this individual. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 + /** Alias for calling [Builder.annualMaximum] with `annualMaximum.orElse(null)`. */ fun annualMaximum(annualMaximum: Optional) = - annualMaximum(annualMaximum.orElse(null) as Long?) + annualMaximum(annualMaximum.getOrNull()) - /** If the benefit supports annual maximum, the amount in cents for this individual. */ + /** + * Sets [Builder.annualMaximum] to an arbitrary JSON value. + * + * You should usually call [Builder.annualMaximum] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun annualMaximum(annualMaximum: JsonField) = apply { this.annualMaximum = annualMaximum } @@ -259,30 +396,41 @@ private constructor( fun catchUp(catchUp: Boolean?) = catchUp(JsonField.ofNullable(catchUp)) /** - * If the benefit supports catch up (401k, 403b, etc.), whether catch up is enabled for - * this individual. + * Alias for [Builder.catchUp]. + * + * This unboxed primitive overload exists for backwards compatibility. */ fun catchUp(catchUp: Boolean) = catchUp(catchUp as Boolean?) - /** - * If the benefit supports catch up (401k, 403b, etc.), whether catch up is enabled for - * this individual. - */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun catchUp(catchUp: Optional) = catchUp(catchUp.orElse(null) as Boolean?) + /** Alias for calling [Builder.catchUp] with `catchUp.orElse(null)`. */ + fun catchUp(catchUp: Optional) = catchUp(catchUp.getOrNull()) /** - * If the benefit supports catch up (401k, 403b, etc.), whether catch up is enabled for - * this individual. + * Sets [Builder.catchUp] to an arbitrary JSON value. + * + * You should usually call [Builder.catchUp] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun catchUp(catchUp: JsonField) = apply { this.catchUp = catchUp } fun companyContribution(companyContribution: BenefitContribution?) = companyContribution(JsonField.ofNullable(companyContribution)) + /** + * Alias for calling [Builder.companyContribution] with + * `companyContribution.orElse(null)`. + */ fun companyContribution(companyContribution: Optional) = - companyContribution(companyContribution.orElse(null)) + companyContribution(companyContribution.getOrNull()) + /** + * Sets [Builder.companyContribution] to an arbitrary JSON value. + * + * You should usually call [Builder.companyContribution] with a well-typed + * [BenefitContribution] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun companyContribution(companyContribution: JsonField) = apply { this.companyContribution = companyContribution } @@ -290,9 +438,19 @@ private constructor( fun employeeDeduction(employeeDeduction: BenefitContribution?) = employeeDeduction(JsonField.ofNullable(employeeDeduction)) + /** + * Alias for calling [Builder.employeeDeduction] with `employeeDeduction.orElse(null)`. + */ fun employeeDeduction(employeeDeduction: Optional) = - employeeDeduction(employeeDeduction.orElse(null)) + employeeDeduction(employeeDeduction.getOrNull()) + /** + * Sets [Builder.employeeDeduction] to an arbitrary JSON value. + * + * You should usually call [Builder.employeeDeduction] with a well-typed + * [BenefitContribution] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun employeeDeduction(employeeDeduction: JsonField) = apply { this.employeeDeduction = employeeDeduction } @@ -301,11 +459,20 @@ private constructor( fun hsaContributionLimit(hsaContributionLimit: HsaContributionLimit?) = hsaContributionLimit(JsonField.ofNullable(hsaContributionLimit)) - /** Type for HSA contribution limit if the benefit is a HSA. */ + /** + * Alias for calling [Builder.hsaContributionLimit] with + * `hsaContributionLimit.orElse(null)`. + */ fun hsaContributionLimit(hsaContributionLimit: Optional) = - hsaContributionLimit(hsaContributionLimit.orElse(null)) + hsaContributionLimit(hsaContributionLimit.getOrNull()) - /** Type for HSA contribution limit if the benefit is a HSA. */ + /** + * Sets [Builder.hsaContributionLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.hsaContributionLimit] with a well-typed + * [HsaContributionLimit] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun hsaContributionLimit(hsaContributionLimit: JsonField) = apply { this.hsaContributionLimit = hsaContributionLimit @@ -330,6 +497,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Body = Body( annualMaximum, @@ -337,10 +509,47 @@ private constructor( companyContribution, employeeDeduction, hsaContributionLimit, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + annualMaximum() + catchUp() + companyContribution().ifPresent { it.validate() } + employeeDeduction().ifPresent { it.validate() } + hsaContributionLimit().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (annualMaximum.asKnown().isPresent) 1 else 0) + + (if (catchUp.asKnown().isPresent) 1 else 0) + + (companyContribution.asKnown().getOrNull()?.validity() ?: 0) + + (employeeDeduction.asKnown().getOrNull()?.validity() ?: 0) + + (hsaContributionLimit.asKnown().getOrNull()?.validity() ?: 0) + /** Type for HSA contribution limit if the benefit is a HSA. */ class HsaContributionLimit @JsonCreator @@ -436,6 +645,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): HsaContributionLimit = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualEnrolledIdsResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualEnrolledIdsResponse.kt index 4d93c7c2..f7f80b94 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualEnrolledIdsResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualEnrolledIdsResponse.kt @@ -10,55 +10,83 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class IndividualEnrolledIdsResponse -@JsonCreator private constructor( - @JsonProperty("benefit_id") - @ExcludeMissing - private val benefitId: JsonField = JsonMissing.of(), - @JsonProperty("individual_ids") - @ExcludeMissing - private val individualIds: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val benefitId: JsonField, + private val individualIds: JsonField>, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("benefit_id") @ExcludeMissing benefitId: JsonField = JsonMissing.of(), + @JsonProperty("individual_ids") + @ExcludeMissing + individualIds: JsonField> = JsonMissing.of(), + ) : this(benefitId, individualIds, mutableMapOf()) + + /** + * The id of the benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun benefitId(): String = benefitId.getRequired("benefit_id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun individualIds(): List = individualIds.getRequired("individual_ids") + /** + * Returns the raw JSON value of [benefitId]. + * + * Unlike [benefitId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("benefit_id") @ExcludeMissing fun _benefitId(): JsonField = benefitId + /** + * Returns the raw JSON value of [individualIds]. + * + * Unlike [individualIds], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("individual_ids") @ExcludeMissing fun _individualIds(): JsonField> = individualIds + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): IndividualEnrolledIdsResponse = apply { - if (validated) { - return@apply - } - - benefitId() - individualIds() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [IndividualEnrolledIdsResponse]. + * + * The following fields are required: + * ```java + * .benefitId() + * .individualIds() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -76,26 +104,40 @@ private constructor( additionalProperties = individualEnrolledIdsResponse.additionalProperties.toMutableMap() } + /** The id of the benefit. */ fun benefitId(benefitId: String) = benefitId(JsonField.of(benefitId)) + /** + * Sets [Builder.benefitId] to an arbitrary JSON value. + * + * You should usually call [Builder.benefitId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun benefitId(benefitId: JsonField) = apply { this.benefitId = benefitId } fun individualIds(individualIds: List) = individualIds(JsonField.of(individualIds)) + /** + * Sets [Builder.individualIds] to an arbitrary JSON value. + * + * You should usually call [Builder.individualIds] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun individualIds(individualIds: JsonField>) = apply { this.individualIds = individualIds.map { it.toMutableList() } } + /** + * Adds a single [String] to [individualIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addIndividualId(individualId: String) = apply { individualIds = - (individualIds ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(individualId) + (individualIds ?: JsonField.of(mutableListOf())).also { + checkKnown("individualIds", it).add(individualId) } } @@ -118,14 +160,57 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [IndividualEnrolledIdsResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .benefitId() + * .individualIds() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): IndividualEnrolledIdsResponse = IndividualEnrolledIdsResponse( checkRequired("benefitId", benefitId), checkRequired("individualIds", individualIds).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): IndividualEnrolledIdsResponse = apply { + if (validated) { + return@apply + } + + benefitId() + individualIds() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (benefitId.asKnown().isPresent) 1 else 0) + + (individualIds.asKnown().getOrNull()?.size ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualEvent.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualEvent.kt index 16e4a305..a1f96d7b 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualEvent.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualEvent.kt @@ -11,57 +11,85 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class IndividualEvent -@JsonCreator private constructor( - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("data") @ExcludeMissing private val data: JsonField = JsonMissing.of(), - @JsonProperty("event_type") - @ExcludeMissing - private val eventType: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accountId: JsonField, + private val companyId: JsonField, + private val connectionId: JsonField, + private val data: JsonField, + private val eventType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("event_type") + @ExcludeMissing + eventType: JsonField = JsonMissing.of(), + ) : this(accountId, companyId, connectionId, data, eventType, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder() + .accountId(accountId) + .companyId(companyId) + .connectionId(connectionId) + .build() + /** * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") /** * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") - /** Unique Finch ID of the connection associated with the webhook event. */ - fun connectionId(): Optional = - Optional.ofNullable(connectionId.getNullable("connection_id")) + /** + * Unique Finch ID of the connection associated with the webhook event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun connectionId(): Optional = connectionId.getOptional("connection_id") - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") - fun eventType(): Optional = Optional.ofNullable(eventType.getNullable("event_type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun eventType(): Optional = eventType.getOptional("event_type") /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("account_id") @@ -69,53 +97,61 @@ private constructor( fun _accountId(): JsonField = accountId /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [eventType]. + * + * Unlike [eventType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("event_type") @ExcludeMissing fun _eventType(): JsonField = eventType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBaseWebhookEvent(): BaseWebhookEvent = - BaseWebhookEvent.builder() - .accountId(accountId) - .companyId(companyId) - .connectionId(connectionId) - .build() - - private var validated: Boolean = false - - fun validate(): IndividualEvent = apply { - if (validated) { - return@apply - } - - accountId() - companyId() - connectionId() - data().ifPresent { it.validate() } - eventType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [IndividualEvent]. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -147,8 +183,11 @@ private constructor( fun accountId(accountId: String) = accountId(JsonField.of(accountId)) /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } @@ -161,8 +200,11 @@ private constructor( fun companyId(companyId: String) = companyId(JsonField.of(companyId)) /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } @@ -170,17 +212,36 @@ private constructor( /** Unique Finch ID of the connection associated with the webhook event. */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } fun data(data: Data) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun eventType(eventType: EventType) = eventType(JsonField.of(eventType)) + /** + * Sets [Builder.eventType] to an arbitrary JSON value. + * + * You should usually call [Builder.eventType] with a well-typed [EventType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun eventType(eventType: JsonField) = apply { this.eventType = eventType } fun additionalProperties(additionalProperties: Map) = apply { @@ -202,6 +263,19 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [IndividualEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): IndividualEvent = IndividualEvent( checkRequired("accountId", accountId), @@ -209,49 +283,92 @@ private constructor( connectionId, data, eventType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): IndividualEvent = apply { + if (validated) { + return@apply + } + + accountId() + companyId() + connectionId() + data().ifPresent { it.validate() } + eventType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountId.asKnown().isPresent) 1 else 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (eventType.asKnown().getOrNull()?.validity() ?: 0) + class Data - @JsonCreator private constructor( - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val individualId: JsonField, + private val additionalProperties: MutableMap, ) { - /** The ID of the individual related to the event. */ - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) + @JsonCreator + private constructor( + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of() + ) : this(individualId, mutableMapOf()) + + /** + * The ID of the individual related to the event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") - /** The ID of the individual related to the event. */ + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Data = apply { - if (validated) { - return@apply - } - - individualId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Data]. */ @JvmStatic fun builder() = Builder() } @@ -270,7 +387,13 @@ private constructor( /** The ID of the individual related to the event. */ fun individualId(individualId: String) = individualId(JsonField.of(individualId)) - /** The ID of the individual related to the event. */ + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -294,9 +417,42 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Data = Data(individualId, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Data = Data(individualId, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + individualId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (individualId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -407,6 +563,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EventType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualInDirectory.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualInDirectory.kt index fe785bc0..fad446f4 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualInDirectory.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualInDirectory.kt @@ -10,108 +10,161 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class IndividualInDirectory -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("department") - @ExcludeMissing - private val department: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("is_active") - @ExcludeMissing - private val isActive: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), - @JsonProperty("manager") - @ExcludeMissing - private val manager: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val department: JsonField, + private val firstName: JsonField, + private val isActive: JsonField, + private val lastName: JsonField, + private val manager: JsonField, + private val middleName: JsonField, + private val additionalProperties: MutableMap, ) { - /** A stable Finch id (UUID v4) for an individual in the company. */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - /** The department object. */ - fun department(): Optional = - Optional.ofNullable(department.getNullable("department")) - - /** The legal first name of the individual. */ - fun firstName(): Optional = Optional.ofNullable(firstName.getNullable("first_name")) - - /** `true` if the individual is an active employee or contractor at the company. */ - fun isActive(): Optional = Optional.ofNullable(isActive.getNullable("is_active")) - - /** The legal last name of the individual. */ - fun lastName(): Optional = Optional.ofNullable(lastName.getNullable("last_name")) - - /** The manager object. */ - fun manager(): Optional = Optional.ofNullable(manager.getNullable("manager")) - - /** The legal middle name of the individual. */ - fun middleName(): Optional = Optional.ofNullable(middleName.getNullable("middle_name")) - - /** A stable Finch id (UUID v4) for an individual in the company. */ + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("department") + @ExcludeMissing + department: JsonField = JsonMissing.of(), + @JsonProperty("first_name") @ExcludeMissing firstName: JsonField = JsonMissing.of(), + @JsonProperty("is_active") @ExcludeMissing isActive: JsonField = JsonMissing.of(), + @JsonProperty("last_name") @ExcludeMissing lastName: JsonField = JsonMissing.of(), + @JsonProperty("manager") @ExcludeMissing manager: JsonField = JsonMissing.of(), + @JsonProperty("middle_name") + @ExcludeMissing + middleName: JsonField = JsonMissing.of(), + ) : this(id, department, firstName, isActive, lastName, manager, middleName, mutableMapOf()) + + /** + * A stable Finch `id` (UUID v4) for an individual in the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * The department object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun department(): Optional = department.getOptional("department") + + /** + * The legal first name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") + + /** + * `true` if the individual is an active employee or contractor at the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isActive(): Optional = isActive.getOptional("is_active") + + /** + * The legal last name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") + + /** + * The manager object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun manager(): Optional = manager.getOptional("manager") + + /** + * The legal middle name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - /** The department object. */ + /** + * Returns the raw JSON value of [department]. + * + * Unlike [department], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("department") @ExcludeMissing fun _department(): JsonField = department - /** The legal first name of the individual. */ + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName - /** `true` if the individual is an active employee or contractor at the company. */ + /** + * Returns the raw JSON value of [isActive]. + * + * Unlike [isActive], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("is_active") @ExcludeMissing fun _isActive(): JsonField = isActive - /** The legal last name of the individual. */ + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName - /** The manager object. */ + /** + * Returns the raw JSON value of [manager]. + * + * Unlike [manager], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("manager") @ExcludeMissing fun _manager(): JsonField = manager - /** The legal middle name of the individual. */ + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("middle_name") @ExcludeMissing fun _middleName(): JsonField = middleName + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): IndividualInDirectory = apply { - if (validated) { - return@apply - } - - id() - department().ifPresent { it.validate() } - firstName() - isActive() - lastName() - manager().ifPresent { it.validate() } - middleName() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [IndividualInDirectory]. */ @JvmStatic fun builder() = Builder() } @@ -139,68 +192,110 @@ private constructor( additionalProperties = individualInDirectory.additionalProperties.toMutableMap() } - /** A stable Finch id (UUID v4) for an individual in the company. */ + /** A stable Finch `id` (UUID v4) for an individual in the company. */ fun id(id: String) = id(JsonField.of(id)) - /** A stable Finch id (UUID v4) for an individual in the company. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } /** The department object. */ fun department(department: Department?) = department(JsonField.ofNullable(department)) - /** The department object. */ - fun department(department: Optional) = department(department.orElse(null)) + /** Alias for calling [Builder.department] with `department.orElse(null)`. */ + fun department(department: Optional) = department(department.getOrNull()) - /** The department object. */ + /** + * Sets [Builder.department] to an arbitrary JSON value. + * + * You should usually call [Builder.department] with a well-typed [Department] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun department(department: JsonField) = apply { this.department = department } /** The legal first name of the individual. */ fun firstName(firstName: String?) = firstName(JsonField.ofNullable(firstName)) - /** The legal first name of the individual. */ - fun firstName(firstName: Optional) = firstName(firstName.orElse(null)) + /** Alias for calling [Builder.firstName] with `firstName.orElse(null)`. */ + fun firstName(firstName: Optional) = firstName(firstName.getOrNull()) - /** The legal first name of the individual. */ + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun firstName(firstName: JsonField) = apply { this.firstName = firstName } /** `true` if the individual is an active employee or contractor at the company. */ fun isActive(isActive: Boolean?) = isActive(JsonField.ofNullable(isActive)) - /** `true` if the individual is an active employee or contractor at the company. */ + /** + * Alias for [Builder.isActive]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun isActive(isActive: Boolean) = isActive(isActive as Boolean?) - /** `true` if the individual is an active employee or contractor at the company. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun isActive(isActive: Optional) = isActive(isActive.orElse(null) as Boolean?) + /** Alias for calling [Builder.isActive] with `isActive.orElse(null)`. */ + fun isActive(isActive: Optional) = isActive(isActive.getOrNull()) - /** `true` if the individual is an active employee or contractor at the company. */ + /** + * Sets [Builder.isActive] to an arbitrary JSON value. + * + * You should usually call [Builder.isActive] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun isActive(isActive: JsonField) = apply { this.isActive = isActive } /** The legal last name of the individual. */ fun lastName(lastName: String?) = lastName(JsonField.ofNullable(lastName)) - /** The legal last name of the individual. */ - fun lastName(lastName: Optional) = lastName(lastName.orElse(null)) + /** Alias for calling [Builder.lastName] with `lastName.orElse(null)`. */ + fun lastName(lastName: Optional) = lastName(lastName.getOrNull()) - /** The legal last name of the individual. */ + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun lastName(lastName: JsonField) = apply { this.lastName = lastName } /** The manager object. */ fun manager(manager: Manager?) = manager(JsonField.ofNullable(manager)) - /** The manager object. */ - fun manager(manager: Optional) = manager(manager.orElse(null)) + /** Alias for calling [Builder.manager] with `manager.orElse(null)`. */ + fun manager(manager: Optional) = manager(manager.getOrNull()) - /** The manager object. */ + /** + * Sets [Builder.manager] to an arbitrary JSON value. + * + * You should usually call [Builder.manager] with a well-typed [Manager] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun manager(manager: JsonField) = apply { this.manager = manager } /** The legal middle name of the individual. */ fun middleName(middleName: String?) = middleName(JsonField.ofNullable(middleName)) - /** The legal middle name of the individual. */ - fun middleName(middleName: Optional) = middleName(middleName.orElse(null)) + /** Alias for calling [Builder.middleName] with `middleName.orElse(null)`. */ + fun middleName(middleName: Optional) = middleName(middleName.getOrNull()) - /** The legal middle name of the individual. */ + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun middleName(middleName: JsonField) = apply { this.middleName = middleName } fun additionalProperties(additionalProperties: Map) = apply { @@ -222,6 +317,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [IndividualInDirectory]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): IndividualInDirectory = IndividualInDirectory( id, @@ -231,47 +331,92 @@ private constructor( lastName, manager, middleName, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): IndividualInDirectory = apply { + if (validated) { + return@apply + } + + id() + department().ifPresent { it.validate() } + firstName() + isActive() + lastName() + manager().ifPresent { it.validate() } + middleName() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (department.asKnown().getOrNull()?.validity() ?: 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (if (isActive.asKnown().isPresent) 1 else 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (manager.asKnown().getOrNull()?.validity() ?: 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + /** The department object. */ - @NoAutoDetect class Department - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - /** The name of the department. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** The name of the department. */ + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) + + /** + * The name of the department. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Department = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Department]. */ @JvmStatic fun builder() = Builder() } @@ -290,10 +435,16 @@ private constructor( /** The name of the department. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The name of the department. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The name of the department. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = apply { @@ -315,9 +466,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Department = Department(name, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Department]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Department = Department(name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Department = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -337,40 +520,47 @@ private constructor( } /** The manager object. */ - @NoAutoDetect class Manager - @JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val additionalProperties: MutableMap, ) { - /** A stable Finch `id` (UUID v4) for an individual in the company. */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of() + ) : this(id, mutableMapOf()) + + /** + * A stable Finch `id` (UUID v4) for an individual in the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Manager = apply { - if (validated) { - return@apply - } - - id() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Manager]. */ @JvmStatic fun builder() = Builder() } @@ -389,7 +579,13 @@ private constructor( /** A stable Finch `id` (UUID v4) for an individual in the company. */ fun id(id: String) = id(JsonField.of(id)) - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun id(id: JsonField) = apply { this.id = id } fun additionalProperties(additionalProperties: Map) = apply { @@ -411,9 +607,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Manager = Manager(id, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Manager]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Manager = Manager(id, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Manager = apply { + if (validated) { + return@apply + } + + id() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (id.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualResponse.kt index c78a32ba..a01069c2 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualResponse.kt @@ -10,62 +10,85 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class IndividualResponse -@JsonCreator private constructor( - @JsonProperty("body") - @ExcludeMissing - private val body: JsonField = JsonMissing.of(), - @JsonProperty("code") @ExcludeMissing private val code: JsonField = JsonMissing.of(), - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val body: JsonField, + private val code: JsonField, + private val individualId: JsonField, + private val additionalProperties: MutableMap, ) { - fun body(): Optional = Optional.ofNullable(body.getNullable("body")) - - fun code(): Optional = Optional.ofNullable(code.getNullable("code")) - - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) - + @JsonCreator + private constructor( + @JsonProperty("body") @ExcludeMissing body: JsonField = JsonMissing.of(), + @JsonProperty("code") @ExcludeMissing code: JsonField = JsonMissing.of(), + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of(), + ) : this(body, code, individualId, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun body(): Optional = body.getOptional("body") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun code(): Optional = code.getOptional("code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") + + /** + * Returns the raw JSON value of [body]. + * + * Unlike [body], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("body") @ExcludeMissing fun _body(): JsonField = body + /** + * Returns the raw JSON value of [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): IndividualResponse = apply { - if (validated) { - return@apply - } - - body().ifPresent { it.validate() } - code() - individualId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [IndividualResponse]. */ @JvmStatic fun builder() = Builder() } @@ -87,14 +110,33 @@ private constructor( fun body(body: Individual) = body(JsonField.of(body)) + /** + * Sets [Builder.body] to an arbitrary JSON value. + * + * You should usually call [Builder.body] with a well-typed [Individual] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun body(body: JsonField) = apply { this.body = body } fun code(code: Long) = code(JsonField.of(code)) + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun code(code: JsonField) = apply { this.code = code } fun individualId(individualId: String) = individualId(JsonField.of(individualId)) + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -118,10 +160,47 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [IndividualResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): IndividualResponse = - IndividualResponse(body, code, individualId, additionalProperties.toImmutable()) + IndividualResponse(body, code, individualId, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): IndividualResponse = apply { + if (validated) { + return@apply + } + + body().ifPresent { it.validate() } + code() + individualId() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (body.asKnown().getOrNull()?.validity() ?: 0) + + (if (code.asKnown().isPresent) 1 else 0) + + (if (individualId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualUpdateResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualUpdateResponse.kt index cd046d07..e95c9fa9 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualUpdateResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/IndividualUpdateResponse.kt @@ -11,179 +11,288 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class IndividualUpdateResponse -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("dob") @ExcludeMissing private val dob: JsonField = JsonMissing.of(), - @JsonProperty("emails") - @ExcludeMissing - private val emails: JsonField> = JsonMissing.of(), - @JsonProperty("encrypted_ssn") - @ExcludeMissing - private val encryptedSsn: JsonField = JsonMissing.of(), - @JsonProperty("ethnicity") - @ExcludeMissing - private val ethnicity: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("gender") - @ExcludeMissing - private val gender: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), - @JsonProperty("phone_numbers") - @ExcludeMissing - private val phoneNumbers: JsonField> = JsonMissing.of(), - @JsonProperty("preferred_name") - @ExcludeMissing - private val preferredName: JsonField = JsonMissing.of(), - @JsonProperty("residence") - @ExcludeMissing - private val residence: JsonField = JsonMissing.of(), - @JsonProperty("ssn") @ExcludeMissing private val ssn: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val dob: JsonField, + private val emails: JsonField>, + private val encryptedSsn: JsonField, + private val ethnicity: JsonField, + private val firstName: JsonField, + private val gender: JsonField, + private val lastName: JsonField, + private val middleName: JsonField, + private val phoneNumbers: JsonField>, + private val preferredName: JsonField, + private val residence: JsonField, + private val ssn: JsonField, + private val additionalProperties: MutableMap, ) { - /** A stable Finch `id` (UUID v4) for an individual in the company. */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("dob") @ExcludeMissing dob: JsonField = JsonMissing.of(), + @JsonProperty("emails") @ExcludeMissing emails: JsonField> = JsonMissing.of(), + @JsonProperty("encrypted_ssn") + @ExcludeMissing + encryptedSsn: JsonField = JsonMissing.of(), + @JsonProperty("ethnicity") + @ExcludeMissing + ethnicity: JsonField = JsonMissing.of(), + @JsonProperty("first_name") @ExcludeMissing firstName: JsonField = JsonMissing.of(), + @JsonProperty("gender") @ExcludeMissing gender: JsonField = JsonMissing.of(), + @JsonProperty("last_name") @ExcludeMissing lastName: JsonField = JsonMissing.of(), + @JsonProperty("middle_name") + @ExcludeMissing + middleName: JsonField = JsonMissing.of(), + @JsonProperty("phone_numbers") + @ExcludeMissing + phoneNumbers: JsonField> = JsonMissing.of(), + @JsonProperty("preferred_name") + @ExcludeMissing + preferredName: JsonField = JsonMissing.of(), + @JsonProperty("residence") + @ExcludeMissing + residence: JsonField = JsonMissing.of(), + @JsonProperty("ssn") @ExcludeMissing ssn: JsonField = JsonMissing.of(), + ) : this( + id, + dob, + emails, + encryptedSsn, + ethnicity, + firstName, + gender, + lastName, + middleName, + phoneNumbers, + preferredName, + residence, + ssn, + mutableMapOf(), + ) + + /** + * A stable Finch `id` (UUID v4) for an individual in the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") - fun dob(): Optional = Optional.ofNullable(dob.getNullable("dob")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun dob(): Optional = dob.getOptional("dob") - fun emails(): Optional> = Optional.ofNullable(emails.getNullable("emails")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun emails(): Optional> = emails.getOptional("emails") /** * Social Security Number of the individual in **encrypted** format. This field is only * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set in * the body. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun encryptedSsn(): Optional = - Optional.ofNullable(encryptedSsn.getNullable("encrypted_ssn")) + fun encryptedSsn(): Optional = encryptedSsn.getOptional("encrypted_ssn") - /** The EEOC-defined ethnicity of the individual. */ - fun ethnicity(): Optional = Optional.ofNullable(ethnicity.getNullable("ethnicity")) + /** + * The EEOC-defined ethnicity of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun ethnicity(): Optional = ethnicity.getOptional("ethnicity") - /** The legal first name of the individual. */ - fun firstName(): Optional = Optional.ofNullable(firstName.getNullable("first_name")) + /** + * The legal first name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") - /** The gender of the individual. */ - fun gender(): Optional = Optional.ofNullable(gender.getNullable("gender")) + /** + * The gender of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun gender(): Optional = gender.getOptional("gender") - /** The legal last name of the individual. */ - fun lastName(): Optional = Optional.ofNullable(lastName.getNullable("last_name")) + /** + * The legal last name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") - /** The legal middle name of the individual. */ - fun middleName(): Optional = Optional.ofNullable(middleName.getNullable("middle_name")) + /** + * The legal middle name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") - fun phoneNumbers(): Optional> = - Optional.ofNullable(phoneNumbers.getNullable("phone_numbers")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun phoneNumbers(): Optional> = phoneNumbers.getOptional("phone_numbers") - /** The preferred name of the individual. */ - fun preferredName(): Optional = - Optional.ofNullable(preferredName.getNullable("preferred_name")) + /** + * The preferred name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun preferredName(): Optional = preferredName.getOptional("preferred_name") - fun residence(): Optional = Optional.ofNullable(residence.getNullable("residence")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun residence(): Optional = residence.getOptional("residence") /** * Social Security Number of the individual. This field is only available with the `ssn` scope * enabled and the `options: { include: ['ssn'] }` param set in the body. * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun ssn(): Optional = Optional.ofNullable(ssn.getNullable("ssn")) + fun ssn(): Optional = ssn.getOptional("ssn") - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [dob]. + * + * Unlike [dob], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("dob") @ExcludeMissing fun _dob(): JsonField = dob + /** + * Returns the raw JSON value of [emails]. + * + * Unlike [emails], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("emails") @ExcludeMissing fun _emails(): JsonField> = emails /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set in - * the body. + * Returns the raw JSON value of [encryptedSsn]. + * + * Unlike [encryptedSsn], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("encrypted_ssn") @ExcludeMissing fun _encryptedSsn(): JsonField = encryptedSsn - /** The EEOC-defined ethnicity of the individual. */ + /** + * Returns the raw JSON value of [ethnicity]. + * + * Unlike [ethnicity], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("ethnicity") @ExcludeMissing fun _ethnicity(): JsonField = ethnicity - /** The legal first name of the individual. */ + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName - /** The gender of the individual. */ + /** + * Returns the raw JSON value of [gender]. + * + * Unlike [gender], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("gender") @ExcludeMissing fun _gender(): JsonField = gender - /** The legal last name of the individual. */ + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName - /** The legal middle name of the individual. */ + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("middle_name") @ExcludeMissing fun _middleName(): JsonField = middleName + /** + * Returns the raw JSON value of [phoneNumbers]. + * + * Unlike [phoneNumbers], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("phone_numbers") @ExcludeMissing fun _phoneNumbers(): JsonField> = phoneNumbers - /** The preferred name of the individual. */ + /** + * Returns the raw JSON value of [preferredName]. + * + * Unlike [preferredName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("preferred_name") @ExcludeMissing fun _preferredName(): JsonField = preferredName + /** + * Returns the raw JSON value of [residence]. + * + * Unlike [residence], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("residence") @ExcludeMissing fun _residence(): JsonField = residence /** - * Social Security Number of the individual. This field is only available with the `ssn` scope - * enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). + * Returns the raw JSON value of [ssn]. + * + * Unlike [ssn], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("ssn") @ExcludeMissing fun _ssn(): JsonField = ssn + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): IndividualUpdateResponse = apply { - if (validated) { - return@apply - } - - id() - dob() - emails().ifPresent { it.forEach { it.validate() } } - encryptedSsn() - ethnicity() - firstName() - gender() - lastName() - middleName() - phoneNumbers().ifPresent { it.forEach { it?.validate() } } - preferredName() - residence().ifPresent { it.validate() } - ssn() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [IndividualUpdateResponse]. */ @JvmStatic fun builder() = Builder() } @@ -226,33 +335,52 @@ private constructor( /** A stable Finch `id` (UUID v4) for an individual in the company. */ fun id(id: String) = id(JsonField.of(id)) - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun dob(dob: String?) = dob(JsonField.ofNullable(dob)) - fun dob(dob: Optional) = dob(dob.orElse(null)) + /** Alias for calling [Builder.dob] with `dob.orElse(null)`. */ + fun dob(dob: Optional) = dob(dob.getOrNull()) + /** + * Sets [Builder.dob] to an arbitrary JSON value. + * + * You should usually call [Builder.dob] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun dob(dob: JsonField) = apply { this.dob = dob } fun emails(emails: List?) = emails(JsonField.ofNullable(emails)) - fun emails(emails: Optional>) = emails(emails.orElse(null)) + /** Alias for calling [Builder.emails] with `emails.orElse(null)`. */ + fun emails(emails: Optional>) = emails(emails.getOrNull()) + /** + * Sets [Builder.emails] to an arbitrary JSON value. + * + * You should usually call [Builder.emails] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun emails(emails: JsonField>) = apply { this.emails = emails.map { it.toMutableList() } } + /** + * Adds a single [Email] to [emails]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addEmail(email: Email) = apply { emails = - (emails ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(email) + (emails ?: JsonField.of(mutableListOf())).also { + checkKnown("emails", it).add(email) } } @@ -263,17 +391,15 @@ private constructor( */ fun encryptedSsn(encryptedSsn: String?) = encryptedSsn(JsonField.ofNullable(encryptedSsn)) - /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set - * in the body. - */ - fun encryptedSsn(encryptedSsn: Optional) = encryptedSsn(encryptedSsn.orElse(null)) + /** Alias for calling [Builder.encryptedSsn] with `encryptedSsn.orElse(null)`. */ + fun encryptedSsn(encryptedSsn: Optional) = encryptedSsn(encryptedSsn.getOrNull()) /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set - * in the body. + * Sets [Builder.encryptedSsn] to an arbitrary JSON value. + * + * You should usually call [Builder.encryptedSsn] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ fun encryptedSsn(encryptedSsn: JsonField) = apply { this.encryptedSsn = encryptedSsn @@ -282,68 +408,103 @@ private constructor( /** The EEOC-defined ethnicity of the individual. */ fun ethnicity(ethnicity: Ethnicity?) = ethnicity(JsonField.ofNullable(ethnicity)) - /** The EEOC-defined ethnicity of the individual. */ - fun ethnicity(ethnicity: Optional) = ethnicity(ethnicity.orElse(null)) + /** Alias for calling [Builder.ethnicity] with `ethnicity.orElse(null)`. */ + fun ethnicity(ethnicity: Optional) = ethnicity(ethnicity.getOrNull()) - /** The EEOC-defined ethnicity of the individual. */ + /** + * Sets [Builder.ethnicity] to an arbitrary JSON value. + * + * You should usually call [Builder.ethnicity] with a well-typed [Ethnicity] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun ethnicity(ethnicity: JsonField) = apply { this.ethnicity = ethnicity } /** The legal first name of the individual. */ fun firstName(firstName: String?) = firstName(JsonField.ofNullable(firstName)) - /** The legal first name of the individual. */ - fun firstName(firstName: Optional) = firstName(firstName.orElse(null)) + /** Alias for calling [Builder.firstName] with `firstName.orElse(null)`. */ + fun firstName(firstName: Optional) = firstName(firstName.getOrNull()) - /** The legal first name of the individual. */ + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun firstName(firstName: JsonField) = apply { this.firstName = firstName } /** The gender of the individual. */ fun gender(gender: Gender?) = gender(JsonField.ofNullable(gender)) - /** The gender of the individual. */ - fun gender(gender: Optional) = gender(gender.orElse(null)) + /** Alias for calling [Builder.gender] with `gender.orElse(null)`. */ + fun gender(gender: Optional) = gender(gender.getOrNull()) - /** The gender of the individual. */ + /** + * Sets [Builder.gender] to an arbitrary JSON value. + * + * You should usually call [Builder.gender] with a well-typed [Gender] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun gender(gender: JsonField) = apply { this.gender = gender } /** The legal last name of the individual. */ fun lastName(lastName: String?) = lastName(JsonField.ofNullable(lastName)) - /** The legal last name of the individual. */ - fun lastName(lastName: Optional) = lastName(lastName.orElse(null)) + /** Alias for calling [Builder.lastName] with `lastName.orElse(null)`. */ + fun lastName(lastName: Optional) = lastName(lastName.getOrNull()) - /** The legal last name of the individual. */ + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun lastName(lastName: JsonField) = apply { this.lastName = lastName } /** The legal middle name of the individual. */ fun middleName(middleName: String?) = middleName(JsonField.ofNullable(middleName)) - /** The legal middle name of the individual. */ - fun middleName(middleName: Optional) = middleName(middleName.orElse(null)) + /** Alias for calling [Builder.middleName] with `middleName.orElse(null)`. */ + fun middleName(middleName: Optional) = middleName(middleName.getOrNull()) - /** The legal middle name of the individual. */ + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun middleName(middleName: JsonField) = apply { this.middleName = middleName } fun phoneNumbers(phoneNumbers: List?) = phoneNumbers(JsonField.ofNullable(phoneNumbers)) + /** Alias for calling [Builder.phoneNumbers] with `phoneNumbers.orElse(null)`. */ fun phoneNumbers(phoneNumbers: Optional>) = - phoneNumbers(phoneNumbers.orElse(null)) + phoneNumbers(phoneNumbers.getOrNull()) + /** + * Sets [Builder.phoneNumbers] to an arbitrary JSON value. + * + * You should usually call [Builder.phoneNumbers] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun phoneNumbers(phoneNumbers: JsonField>) = apply { this.phoneNumbers = phoneNumbers.map { it.toMutableList() } } + /** + * Adds a single [PhoneNumber] to [phoneNumbers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addPhoneNumber(phoneNumber: PhoneNumber) = apply { phoneNumbers = - (phoneNumbers ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(phoneNumber) + (phoneNumbers ?: JsonField.of(mutableListOf())).also { + checkKnown("phoneNumbers", it).add(phoneNumber) } } @@ -351,19 +512,33 @@ private constructor( fun preferredName(preferredName: String?) = preferredName(JsonField.ofNullable(preferredName)) - /** The preferred name of the individual. */ + /** Alias for calling [Builder.preferredName] with `preferredName.orElse(null)`. */ fun preferredName(preferredName: Optional) = - preferredName(preferredName.orElse(null)) + preferredName(preferredName.getOrNull()) - /** The preferred name of the individual. */ + /** + * Sets [Builder.preferredName] to an arbitrary JSON value. + * + * You should usually call [Builder.preferredName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun preferredName(preferredName: JsonField) = apply { this.preferredName = preferredName } fun residence(residence: Location?) = residence(JsonField.ofNullable(residence)) - fun residence(residence: Optional) = residence(residence.orElse(null)) + /** Alias for calling [Builder.residence] with `residence.orElse(null)`. */ + fun residence(residence: Optional) = residence(residence.getOrNull()) + /** + * Sets [Builder.residence] to an arbitrary JSON value. + * + * You should usually call [Builder.residence] with a well-typed [Location] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun residence(residence: JsonField) = apply { this.residence = residence } /** @@ -373,17 +548,14 @@ private constructor( */ fun ssn(ssn: String?) = ssn(JsonField.ofNullable(ssn)) - /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). - */ - fun ssn(ssn: Optional) = ssn(ssn.orElse(null)) + /** Alias for calling [Builder.ssn] with `ssn.orElse(null)`. */ + fun ssn(ssn: Optional) = ssn(ssn.getOrNull()) /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). + * Sets [Builder.ssn] to an arbitrary JSON value. + * + * You should usually call [Builder.ssn] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun ssn(ssn: JsonField) = apply { this.ssn = ssn } @@ -406,6 +578,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [IndividualUpdateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): IndividualUpdateResponse = IndividualUpdateResponse( id, @@ -421,50 +598,116 @@ private constructor( preferredName, residence, ssn, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): IndividualUpdateResponse = apply { + if (validated) { + return@apply + } + + id() + dob() + emails().ifPresent { it.forEach { it.validate() } } + encryptedSsn() + ethnicity().ifPresent { it.validate() } + firstName() + gender().ifPresent { it.validate() } + lastName() + middleName() + phoneNumbers().ifPresent { it.forEach { it?.validate() } } + preferredName() + residence().ifPresent { it.validate() } + ssn() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (dob.asKnown().isPresent) 1 else 0) + + (emails.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (encryptedSsn.asKnown().isPresent) 1 else 0) + + (ethnicity.asKnown().getOrNull()?.validity() ?: 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (gender.asKnown().getOrNull()?.validity() ?: 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + + (phoneNumbers.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (preferredName.asKnown().isPresent) 1 else 0) + + (residence.asKnown().getOrNull()?.validity() ?: 0) + + (if (ssn.asKnown().isPresent) 1 else 0) + class Email - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Email = apply { - if (validated) { - return@apply - } - - data() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Email]. */ @JvmStatic fun builder() = Builder() } @@ -484,12 +727,27 @@ private constructor( fun data(data: String) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun data(data: JsonField) = apply { this.data = data } fun type(type: Type?) = type(JsonField.ofNullable(type)) - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -511,9 +769,44 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Email = Email(data, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Email]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Email = Email(data, type, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Email = apply { + if (validated) { + return@apply + } + + data() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -601,6 +894,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -756,6 +1076,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Ethnicity = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -866,6 +1213,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Gender = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -879,46 +1253,60 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class PhoneNumber - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PhoneNumber = apply { - if (validated) { - return@apply - } - - data() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [PhoneNumber]. */ @JvmStatic fun builder() = Builder() } @@ -936,14 +1324,32 @@ private constructor( additionalProperties = phoneNumber.additionalProperties.toMutableMap() } - fun data(data: String) = data(JsonField.of(data)) + fun data(data: String?) = data(JsonField.ofNullable(data)) + /** Alias for calling [Builder.data] with `data.orElse(null)`. */ + fun data(data: Optional) = data(data.getOrNull()) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun data(data: JsonField) = apply { this.data = data } fun type(type: Type?) = type(JsonField.ofNullable(type)) - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -965,9 +1371,44 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): PhoneNumber = PhoneNumber(data, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [PhoneNumber]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): PhoneNumber = PhoneNumber(data, type, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): PhoneNumber = apply { + if (validated) { + return@apply + } + + data() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -1055,6 +1496,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Introspection.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Introspection.kt index d3ea4304..bf5a6265 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Introspection.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Introspection.kt @@ -11,270 +11,406 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class Introspection -@JsonCreator private constructor( - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("authentication_methods") - @ExcludeMissing - private val authenticationMethods: JsonField> = JsonMissing.of(), - @JsonProperty("client_id") - @ExcludeMissing - private val clientId: JsonField = JsonMissing.of(), - @JsonProperty("client_type") - @ExcludeMissing - private val clientType: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("connection_status") - @ExcludeMissing - private val connectionStatus: JsonField = JsonMissing.of(), - @JsonProperty("connection_type") - @ExcludeMissing - private val connectionType: JsonField = JsonMissing.of(), - @JsonProperty("customer_email") - @ExcludeMissing - private val customerEmail: JsonField = JsonMissing.of(), - @JsonProperty("customer_id") - @ExcludeMissing - private val customerId: JsonField = JsonMissing.of(), - @JsonProperty("customer_name") - @ExcludeMissing - private val customerName: JsonField = JsonMissing.of(), - @JsonProperty("manual") - @ExcludeMissing - private val manual: JsonField = JsonMissing.of(), - @JsonProperty("payroll_provider_id") - @ExcludeMissing - private val payrollProviderId: JsonField = JsonMissing.of(), - @JsonProperty("products") - @ExcludeMissing - private val products: JsonField> = JsonMissing.of(), - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonProperty("username") - @ExcludeMissing - private val username: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accountId: JsonField, + private val authenticationMethods: JsonField>, + private val clientId: JsonField, + private val clientType: JsonField, + private val companyId: JsonField, + private val connectionId: JsonField, + private val connectionStatus: JsonField, + private val connectionType: JsonField, + private val customerEmail: JsonField, + private val customerId: JsonField, + private val customerName: JsonField, + private val manual: JsonField, + private val payrollProviderId: JsonField, + private val products: JsonField>, + private val providerId: JsonField, + private val username: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("authentication_methods") + @ExcludeMissing + authenticationMethods: JsonField> = JsonMissing.of(), + @JsonProperty("client_id") @ExcludeMissing clientId: JsonField = JsonMissing.of(), + @JsonProperty("client_type") + @ExcludeMissing + clientType: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("connection_status") + @ExcludeMissing + connectionStatus: JsonField = JsonMissing.of(), + @JsonProperty("connection_type") + @ExcludeMissing + connectionType: JsonField = JsonMissing.of(), + @JsonProperty("customer_email") + @ExcludeMissing + customerEmail: JsonField = JsonMissing.of(), + @JsonProperty("customer_id") + @ExcludeMissing + customerId: JsonField = JsonMissing.of(), + @JsonProperty("customer_name") + @ExcludeMissing + customerName: JsonField = JsonMissing.of(), + @JsonProperty("manual") @ExcludeMissing manual: JsonField = JsonMissing.of(), + @JsonProperty("payroll_provider_id") + @ExcludeMissing + payrollProviderId: JsonField = JsonMissing.of(), + @JsonProperty("products") + @ExcludeMissing + products: JsonField> = JsonMissing.of(), + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + @JsonProperty("username") @ExcludeMissing username: JsonField = JsonMissing.of(), + ) : this( + accountId, + authenticationMethods, + clientId, + clientType, + companyId, + connectionId, + connectionStatus, + connectionType, + customerEmail, + customerId, + customerName, + manual, + payrollProviderId, + products, + providerId, + username, + mutableMapOf(), + ) + /** * [DEPRECATED] Use `connection_id` to associate tokens with a Finch connection instead of this * account ID. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun authenticationMethods(): List = authenticationMethods.getRequired("authentication_methods") - /** The client ID of the application associated with the `access_token`. */ + /** + * The client ID of the application associated with the `access_token`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun clientId(): String = clientId.getRequired("client_id") - /** The type of application associated with a token. */ + /** + * The type of application associated with a token. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun clientType(): ClientType = clientType.getRequired("client_type") /** * [DEPRECATED] Use `connection_id` to associate tokens with a Finch connection instead of this * company ID. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") - /** The Finch UUID of the connection associated with the `access_token`. */ + /** + * The Finch UUID of the connection associated with the `access_token`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun connectionId(): String = connectionId.getRequired("connection_id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun connectionStatus(): ConnectionStatus = connectionStatus.getRequired("connection_status") /** * The type of the connection associated with the token. * - `provider` - connection to an external provider * - `finch` - finch-generated data. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ fun connectionType(): ConnectionType = connectionType.getRequired("connection_type") /** * The email of your customer you provided to Finch when a connect session was created for this * connection. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun customerEmail(): Optional = - Optional.ofNullable(customerEmail.getNullable("customer_email")) + fun customerEmail(): Optional = customerEmail.getOptional("customer_email") /** * The ID of your customer you provided to Finch when a connect session was created for this * connection. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun customerId(): Optional = Optional.ofNullable(customerId.getNullable("customer_id")) + fun customerId(): Optional = customerId.getOptional("customer_id") /** * The name of your customer you provided to Finch when a connect session was created for this * connection. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun customerName(): Optional = - Optional.ofNullable(customerName.getNullable("customer_name")) + fun customerName(): Optional = customerName.getOptional("customer_name") /** * Whether the connection associated with the `access_token` uses the Assisted Connect Flow. * (`true` if using Assisted Connect, `false` if connection is automated) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ fun manual(): Boolean = manual.getRequired("manual") /** * [DEPRECATED] Use `provider_id` to identify the provider instead of this payroll provider ID. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun payrollProviderId(): String = payrollProviderId.getRequired("payroll_provider_id") - /** An array of the authorized products associated with the `access_token`. */ + /** + * An array of the authorized products associated with the `access_token`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun products(): List = products.getRequired("products") - /** The ID of the provider associated with the `access_token`. */ + /** + * The ID of the provider associated with the `access_token`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun providerId(): String = providerId.getRequired("provider_id") - /** The account username used for login associated with the `access_token`. */ + /** + * The account username used for login associated with the `access_token`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun username(): String = username.getRequired("username") /** - * [DEPRECATED] Use `connection_id` to associate tokens with a Finch connection instead of this - * account ID. + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("account_id") @ExcludeMissing fun _accountId(): JsonField = accountId + /** + * Returns the raw JSON value of [authenticationMethods]. + * + * Unlike [authenticationMethods], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("authentication_methods") @ExcludeMissing fun _authenticationMethods(): JsonField> = authenticationMethods - /** The client ID of the application associated with the `access_token`. */ + /** + * Returns the raw JSON value of [clientId]. + * + * Unlike [clientId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("client_id") @ExcludeMissing fun _clientId(): JsonField = clientId - /** The type of application associated with a token. */ + /** + * Returns the raw JSON value of [clientType]. + * + * Unlike [clientType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("client_type") @ExcludeMissing fun _clientType(): JsonField = clientType /** - * [DEPRECATED] Use `connection_id` to associate tokens with a Finch connection instead of this - * company ID. + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - /** The Finch UUID of the connection associated with the `access_token`. */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId + /** + * Returns the raw JSON value of [connectionStatus]. + * + * Unlike [connectionStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("connection_status") @ExcludeMissing fun _connectionStatus(): JsonField = connectionStatus /** - * The type of the connection associated with the token. - * - `provider` - connection to an external provider - * - `finch` - finch-generated data. + * Returns the raw JSON value of [connectionType]. + * + * Unlike [connectionType], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("connection_type") @ExcludeMissing fun _connectionType(): JsonField = connectionType /** - * The email of your customer you provided to Finch when a connect session was created for this - * connection. + * Returns the raw JSON value of [customerEmail]. + * + * Unlike [customerEmail], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("customer_email") @ExcludeMissing fun _customerEmail(): JsonField = customerEmail /** - * The ID of your customer you provided to Finch when a connect session was created for this - * connection. + * Returns the raw JSON value of [customerId]. + * + * Unlike [customerId], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("customer_id") @ExcludeMissing fun _customerId(): JsonField = customerId /** - * The name of your customer you provided to Finch when a connect session was created for this - * connection. + * Returns the raw JSON value of [customerName]. + * + * Unlike [customerName], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("customer_name") @ExcludeMissing fun _customerName(): JsonField = customerName /** - * Whether the connection associated with the `access_token` uses the Assisted Connect Flow. - * (`true` if using Assisted Connect, `false` if connection is automated) + * Returns the raw JSON value of [manual]. + * + * Unlike [manual], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("manual") @ExcludeMissing fun _manual(): JsonField = manual /** - * [DEPRECATED] Use `provider_id` to identify the provider instead of this payroll provider ID. + * Returns the raw JSON value of [payrollProviderId]. + * + * Unlike [payrollProviderId], this method doesn't throw if the JSON field has an unexpected + * type. */ @Deprecated("deprecated") @JsonProperty("payroll_provider_id") @ExcludeMissing fun _payrollProviderId(): JsonField = payrollProviderId - /** An array of the authorized products associated with the `access_token`. */ + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("products") @ExcludeMissing fun _products(): JsonField> = products - /** The ID of the provider associated with the `access_token`. */ + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("provider_id") @ExcludeMissing fun _providerId(): JsonField = providerId - /** The account username used for login associated with the `access_token`. */ + /** + * Returns the raw JSON value of [username]. + * + * Unlike [username], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("username") @ExcludeMissing fun _username(): JsonField = username + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Introspection = apply { - if (validated) { - return@apply - } - - accountId() - authenticationMethods().forEach { it.validate() } - clientId() - clientType() - companyId() - connectionId() - connectionStatus().validate() - connectionType() - customerEmail() - customerId() - customerName() - manual() - payrollProviderId() - products() - providerId() - username() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Introspection]. + * + * The following fields are required: + * ```java + * .accountId() + * .authenticationMethods() + * .clientId() + * .clientType() + * .companyId() + * .connectionId() + * .connectionStatus() + * .connectionType() + * .customerEmail() + * .customerId() + * .customerName() + * .manual() + * .payrollProviderId() + * .products() + * .providerId() + * .username() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -328,8 +464,11 @@ private constructor( fun accountId(accountId: String) = accountId(JsonField.of(accountId)) /** - * [DEPRECATED] Use `connection_id` to associate tokens with a Finch connection instead of - * this account ID. + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } @@ -337,34 +476,51 @@ private constructor( fun authenticationMethods(authenticationMethods: List) = authenticationMethods(JsonField.of(authenticationMethods)) + /** + * Sets [Builder.authenticationMethods] to an arbitrary JSON value. + * + * You should usually call [Builder.authenticationMethods] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun authenticationMethods(authenticationMethods: JsonField>) = apply { this.authenticationMethods = authenticationMethods.map { it.toMutableList() } } + /** + * Adds a single [AuthenticationMethod] to [authenticationMethods]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addAuthenticationMethod(authenticationMethod: AuthenticationMethod) = apply { authenticationMethods = - (authenticationMethods ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(authenticationMethod) + (authenticationMethods ?: JsonField.of(mutableListOf())).also { + checkKnown("authenticationMethods", it).add(authenticationMethod) } } /** The client ID of the application associated with the `access_token`. */ fun clientId(clientId: String) = clientId(JsonField.of(clientId)) - /** The client ID of the application associated with the `access_token`. */ + /** + * Sets [Builder.clientId] to an arbitrary JSON value. + * + * You should usually call [Builder.clientId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun clientId(clientId: JsonField) = apply { this.clientId = clientId } /** The type of application associated with a token. */ fun clientType(clientType: ClientType) = clientType(JsonField.of(clientType)) - /** The type of application associated with a token. */ + /** + * Sets [Builder.clientType] to an arbitrary JSON value. + * + * You should usually call [Builder.clientType] with a well-typed [ClientType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun clientType(clientType: JsonField) = apply { this.clientType = clientType } /** @@ -375,8 +531,11 @@ private constructor( fun companyId(companyId: String) = companyId(JsonField.of(companyId)) /** - * [DEPRECATED] Use `connection_id` to associate tokens with a Finch connection instead of - * this company ID. + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } @@ -384,7 +543,13 @@ private constructor( /** The Finch UUID of the connection associated with the `access_token`. */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** The Finch UUID of the connection associated with the `access_token`. */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } @@ -392,6 +557,13 @@ private constructor( fun connectionStatus(connectionStatus: ConnectionStatus) = connectionStatus(JsonField.of(connectionStatus)) + /** + * Sets [Builder.connectionStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionStatus] with a well-typed [ConnectionStatus] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun connectionStatus(connectionStatus: JsonField) = apply { this.connectionStatus = connectionStatus } @@ -405,9 +577,11 @@ private constructor( connectionType(JsonField.of(connectionType)) /** - * The type of the connection associated with the token. - * - `provider` - connection to an external provider - * - `finch` - finch-generated data. + * Sets [Builder.connectionType] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionType] with a well-typed [ConnectionType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun connectionType(connectionType: JsonField) = apply { this.connectionType = connectionType @@ -420,16 +594,16 @@ private constructor( fun customerEmail(customerEmail: String?) = customerEmail(JsonField.ofNullable(customerEmail)) - /** - * The email of your customer you provided to Finch when a connect session was created for - * this connection. - */ + /** Alias for calling [Builder.customerEmail] with `customerEmail.orElse(null)`. */ fun customerEmail(customerEmail: Optional) = - customerEmail(customerEmail.orElse(null)) + customerEmail(customerEmail.getOrNull()) /** - * The email of your customer you provided to Finch when a connect session was created for - * this connection. + * Sets [Builder.customerEmail] to an arbitrary JSON value. + * + * You should usually call [Builder.customerEmail] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ fun customerEmail(customerEmail: JsonField) = apply { this.customerEmail = customerEmail @@ -441,15 +615,15 @@ private constructor( */ fun customerId(customerId: String?) = customerId(JsonField.ofNullable(customerId)) - /** - * The ID of your customer you provided to Finch when a connect session was created for this - * connection. - */ - fun customerId(customerId: Optional) = customerId(customerId.orElse(null)) + /** Alias for calling [Builder.customerId] with `customerId.orElse(null)`. */ + fun customerId(customerId: Optional) = customerId(customerId.getOrNull()) /** - * The ID of your customer you provided to Finch when a connect session was created for this - * connection. + * Sets [Builder.customerId] to an arbitrary JSON value. + * + * You should usually call [Builder.customerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ fun customerId(customerId: JsonField) = apply { this.customerId = customerId } @@ -459,15 +633,15 @@ private constructor( */ fun customerName(customerName: String?) = customerName(JsonField.ofNullable(customerName)) - /** - * The name of your customer you provided to Finch when a connect session was created for - * this connection. - */ - fun customerName(customerName: Optional) = customerName(customerName.orElse(null)) + /** Alias for calling [Builder.customerName] with `customerName.orElse(null)`. */ + fun customerName(customerName: Optional) = customerName(customerName.getOrNull()) /** - * The name of your customer you provided to Finch when a connect session was created for - * this connection. + * Sets [Builder.customerName] to an arbitrary JSON value. + * + * You should usually call [Builder.customerName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ fun customerName(customerName: JsonField) = apply { this.customerName = customerName @@ -480,8 +654,10 @@ private constructor( fun manual(manual: Boolean) = manual(JsonField.of(manual)) /** - * Whether the connection associated with the `access_token` uses the Assisted Connect Flow. - * (`true` if using Assisted Connect, `false` if connection is automated) + * Sets [Builder.manual] to an arbitrary JSON value. + * + * You should usually call [Builder.manual] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun manual(manual: JsonField) = apply { this.manual = manual } @@ -494,8 +670,11 @@ private constructor( payrollProviderId(JsonField.of(payrollProviderId)) /** - * [DEPRECATED] Use `provider_id` to identify the provider instead of this payroll provider - * ID. + * Sets [Builder.payrollProviderId] to an arbitrary JSON value. + * + * You should usually call [Builder.payrollProviderId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ @Deprecated("deprecated") fun payrollProviderId(payrollProviderId: JsonField) = apply { @@ -505,35 +684,50 @@ private constructor( /** An array of the authorized products associated with the `access_token`. */ fun products(products: List) = products(JsonField.of(products)) - /** An array of the authorized products associated with the `access_token`. */ + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun products(products: JsonField>) = apply { this.products = products.map { it.toMutableList() } } - /** An array of the authorized products associated with the `access_token`. */ + /** + * Adds a single [String] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addProduct(product: String) = apply { products = - (products ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(product) + (products ?: JsonField.of(mutableListOf())).also { + checkKnown("products", it).add(product) } } /** The ID of the provider associated with the `access_token`. */ fun providerId(providerId: String) = providerId(JsonField.of(providerId)) - /** The ID of the provider associated with the `access_token`. */ + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun providerId(providerId: JsonField) = apply { this.providerId = providerId } /** The account username used for login associated with the `access_token`. */ fun username(username: String) = username(JsonField.of(username)) - /** The account username used for login associated with the `access_token`. */ + /** + * Sets [Builder.username] to an arbitrary JSON value. + * + * You should usually call [Builder.username] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun username(username: JsonField) = apply { this.username = username } fun additionalProperties(additionalProperties: Map) = apply { @@ -555,6 +749,33 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Introspection]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accountId() + * .authenticationMethods() + * .clientId() + * .clientType() + * .companyId() + * .connectionId() + * .connectionStatus() + * .connectionType() + * .customerEmail() + * .customerId() + * .customerName() + * .manual() + * .payrollProviderId() + * .products() + * .providerId() + * .username() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Introspection = Introspection( checkRequired("accountId", accountId), @@ -575,68 +796,151 @@ private constructor( checkRequired("products", products).map { it.toImmutable() }, checkRequired("providerId", providerId), checkRequired("username", username), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Introspection = apply { + if (validated) { + return@apply + } + + accountId() + authenticationMethods().forEach { it.validate() } + clientId() + clientType().validate() + companyId() + connectionId() + connectionStatus().validate() + connectionType().validate() + customerEmail() + customerId() + customerName() + manual() + payrollProviderId() + products() + providerId() + username() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountId.asKnown().isPresent) 1 else 0) + + (authenticationMethods.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (clientId.asKnown().isPresent) 1 else 0) + + (clientType.asKnown().getOrNull()?.validity() ?: 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + + (connectionStatus.asKnown().getOrNull()?.validity() ?: 0) + + (connectionType.asKnown().getOrNull()?.validity() ?: 0) + + (if (customerEmail.asKnown().isPresent) 1 else 0) + + (if (customerId.asKnown().isPresent) 1 else 0) + + (if (customerName.asKnown().isPresent) 1 else 0) + + (if (manual.asKnown().isPresent) 1 else 0) + + (if (payrollProviderId.asKnown().isPresent) 1 else 0) + + (products.asKnown().getOrNull()?.size ?: 0) + + (if (providerId.asKnown().isPresent) 1 else 0) + + (if (username.asKnown().isPresent) 1 else 0) + class AuthenticationMethod - @JsonCreator private constructor( - @JsonProperty("connection_status") - @ExcludeMissing - private val connectionStatus: JsonField = JsonMissing.of(), - @JsonProperty("products") - @ExcludeMissing - private val products: JsonField> = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val connectionStatus: JsonField, + private val products: JsonField>, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("connection_status") + @ExcludeMissing + connectionStatus: JsonField = JsonMissing.of(), + @JsonProperty("products") + @ExcludeMissing + products: JsonField> = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(connectionStatus, products, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun connectionStatus(): Optional = - Optional.ofNullable(connectionStatus.getNullable("connection_status")) + connectionStatus.getOptional("connection_status") - /** An array of the authorized products associated with the `access_token`. */ - fun products(): Optional> = - Optional.ofNullable(products.getNullable("products")) + /** + * An array of the authorized products associated with the `access_token`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun products(): Optional> = products.getOptional("products") - /** The type of authentication method. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The type of authentication method. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + /** + * Returns the raw JSON value of [connectionStatus]. + * + * Unlike [connectionStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("connection_status") @ExcludeMissing fun _connectionStatus(): JsonField = connectionStatus - /** An array of the authorized products associated with the `access_token`. */ + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("products") @ExcludeMissing fun _products(): JsonField> = products - /** The type of authentication method. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AuthenticationMethod = apply { - if (validated) { - return@apply - } - - connectionStatus().ifPresent { it.validate() } - products() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [AuthenticationMethod]. */ @JvmStatic fun builder() = Builder() } @@ -659,6 +963,13 @@ private constructor( fun connectionStatus(connectionStatus: ConnectionStatus) = connectionStatus(JsonField.of(connectionStatus)) + /** + * Sets [Builder.connectionStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionStatus] with a well-typed + * [ConnectionStatus] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ fun connectionStatus(connectionStatus: JsonField) = apply { this.connectionStatus = connectionStatus } @@ -666,29 +977,39 @@ private constructor( /** An array of the authorized products associated with the `access_token`. */ fun products(products: List) = products(JsonField.of(products)) - /** An array of the authorized products associated with the `access_token`. */ + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun products(products: JsonField>) = apply { this.products = products.map { it.toMutableList() } } - /** An array of the authorized products associated with the `access_token`. */ + /** + * Adds a single [String] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addProduct(product: String) = apply { products = - (products ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(product) + (products ?: JsonField.of(mutableListOf())).also { + checkKnown("products", it).add(product) } } /** The type of authentication method. */ fun type(type: Type) = type(JsonField.of(type)) - /** The type of authentication method. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -710,60 +1031,113 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [AuthenticationMethod]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): AuthenticationMethod = AuthenticationMethod( connectionStatus, (products ?: JsonMissing.of()).map { it.toImmutable() }, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): AuthenticationMethod = apply { + if (validated) { + return@apply + } + + connectionStatus().ifPresent { it.validate() } + products() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (connectionStatus.asKnown().getOrNull()?.validity() ?: 0) + + (products.asKnown().getOrNull()?.size ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class ConnectionStatus - @JsonCreator private constructor( - @JsonProperty("message") - @ExcludeMissing - private val message: JsonField = JsonMissing.of(), - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val message: JsonField, + private val status: JsonField, + private val additionalProperties: MutableMap, ) { - fun message(): Optional = Optional.ofNullable(message.getNullable("message")) + @JsonCreator + private constructor( + @JsonProperty("message") + @ExcludeMissing + message: JsonField = JsonMissing.of(), + @JsonProperty("status") + @ExcludeMissing + status: JsonField = JsonMissing.of(), + ) : this(message, status, mutableMapOf()) - fun status(): Optional = - Optional.ofNullable(status.getNullable("status")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun message(): Optional = message.getOptional("message") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun status(): Optional = status.getOptional("status") + /** + * Returns the raw JSON value of [message]. + * + * Unlike [message], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message + /** + * Returns the raw JSON value of [status]. + * + * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ConnectionStatus = apply { - if (validated) { - return@apply - } - - message() - status() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [ConnectionStatus]. */ @JvmStatic fun builder() = Builder() } @@ -783,10 +1157,24 @@ private constructor( fun message(message: String) = message(JsonField.of(message)) + /** + * Sets [Builder.message] to an arbitrary JSON value. + * + * You should usually call [Builder.message] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun message(message: JsonField) = apply { this.message = message } fun status(status: ConnectionStatusType) = status(JsonField.of(status)) + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [ConnectionStatusType] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ fun status(status: JsonField) = apply { this.status = status } fun additionalProperties(additionalProperties: Map) = apply { @@ -811,10 +1199,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [ConnectionStatus]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ConnectionStatus = - ConnectionStatus(message, status, additionalProperties.toImmutable()) + ConnectionStatus(message, status, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): ConnectionStatus = apply { + if (validated) { + return@apply + } + + message() + status().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (message.asKnown().isPresent) 1 else 0) + + (status.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -939,6 +1363,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1063,6 +1514,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ClientType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1076,74 +1554,141 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class ConnectionStatus - @JsonCreator private constructor( - @JsonProperty("message") - @ExcludeMissing - private val message: JsonField = JsonMissing.of(), - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val lastSuccessfulSync: JsonField, + private val message: JsonField, + private val status: JsonField, + private val additionalProperties: MutableMap, ) { - fun message(): Optional = Optional.ofNullable(message.getNullable("message")) + @JsonCreator + private constructor( + @JsonProperty("last_successful_sync") + @ExcludeMissing + lastSuccessfulSync: JsonField = JsonMissing.of(), + @JsonProperty("message") @ExcludeMissing message: JsonField = JsonMissing.of(), + @JsonProperty("status") + @ExcludeMissing + status: JsonField = JsonMissing.of(), + ) : this(lastSuccessfulSync, message, status, mutableMapOf()) + + /** + * The datetime when the connection was last successfully synced. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun lastSuccessfulSync(): Optional = + lastSuccessfulSync.getOptional("last_successful_sync") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun message(): Optional = message.getOptional("message") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun status(): Optional = status.getOptional("status") - fun status(): Optional = - Optional.ofNullable(status.getNullable("status")) + /** + * Returns the raw JSON value of [lastSuccessfulSync]. + * + * Unlike [lastSuccessfulSync], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("last_successful_sync") + @ExcludeMissing + fun _lastSuccessfulSync(): JsonField = lastSuccessfulSync + /** + * Returns the raw JSON value of [message]. + * + * Unlike [message], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message + /** + * Returns the raw JSON value of [status]. + * + * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ConnectionStatus = apply { - if (validated) { - return@apply - } - - message() - status() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [ConnectionStatus]. */ @JvmStatic fun builder() = Builder() } /** A builder for [ConnectionStatus]. */ class Builder internal constructor() { + private var lastSuccessfulSync: JsonField = JsonMissing.of() private var message: JsonField = JsonMissing.of() private var status: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(connectionStatus: ConnectionStatus) = apply { + lastSuccessfulSync = connectionStatus.lastSuccessfulSync message = connectionStatus.message status = connectionStatus.status additionalProperties = connectionStatus.additionalProperties.toMutableMap() } + /** The datetime when the connection was last successfully synced. */ + fun lastSuccessfulSync(lastSuccessfulSync: OffsetDateTime) = + lastSuccessfulSync(JsonField.of(lastSuccessfulSync)) + + /** + * Sets [Builder.lastSuccessfulSync] to an arbitrary JSON value. + * + * You should usually call [Builder.lastSuccessfulSync] with a well-typed + * [OffsetDateTime] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun lastSuccessfulSync(lastSuccessfulSync: JsonField) = apply { + this.lastSuccessfulSync = lastSuccessfulSync + } + fun message(message: String) = message(JsonField.of(message)) + /** + * Sets [Builder.message] to an arbitrary JSON value. + * + * You should usually call [Builder.message] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun message(message: JsonField) = apply { this.message = message } fun status(status: ConnectionStatusType) = status(JsonField.of(status)) + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [ConnectionStatusType] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun status(status: JsonField) = apply { this.status = status } fun additionalProperties(additionalProperties: Map) = apply { @@ -1165,26 +1710,69 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [ConnectionStatus]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ConnectionStatus = - ConnectionStatus(message, status, additionalProperties.toImmutable()) + ConnectionStatus( + lastSuccessfulSync, + message, + status, + additionalProperties.toMutableMap(), + ) } + private var validated: Boolean = false + + fun validate(): ConnectionStatus = apply { + if (validated) { + return@apply + } + + lastSuccessfulSync() + message() + status().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (lastSuccessfulSync.asKnown().isPresent) 1 else 0) + + (if (message.asKnown().isPresent) 1 else 0) + + (status.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is ConnectionStatus && message == other.message && status == other.status && additionalProperties == other.additionalProperties /* spotless:on */ + return /* spotless:off */ other is ConnectionStatus && lastSuccessfulSync == other.lastSuccessfulSync && message == other.message && status == other.status && additionalProperties == other.additionalProperties /* spotless:on */ } /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(message, status, additionalProperties) } + private val hashCode: Int by lazy { Objects.hash(lastSuccessfulSync, message, status, additionalProperties) } /* spotless:on */ override fun hashCode(): Int = hashCode override fun toString() = - "ConnectionStatus{message=$message, status=$status, additionalProperties=$additionalProperties}" + "ConnectionStatus{lastSuccessfulSync=$lastSuccessfulSync, message=$message, status=$status, additionalProperties=$additionalProperties}" } /** @@ -1280,6 +1868,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): ConnectionType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedCreateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedCreateParams.kt index 34e0c010..ac13130c 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedCreateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedCreateParams.kt @@ -20,15 +20,13 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.getOrThrow import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional import kotlin.jvm.optionals.getOrNull @@ -61,7 +59,169 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Optional = Optional.ofNullable(body) + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): JobAutomatedCreateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [JobAutomatedCreateParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [JobAutomatedCreateParams]. */ + class Builder internal constructor() { + + private var body: Body? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(jobAutomatedCreateParams: JobAutomatedCreateParams) = apply { + body = jobAutomatedCreateParams.body + additionalHeaders = jobAutomatedCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = jobAutomatedCreateParams.additionalQueryParams.toBuilder() + } + + fun body(body: Body?) = apply { this.body = body } + + /** Alias for calling [Builder.body] with `body.orElse(null)`. */ + fun body(body: Optional) = body(body.getOrNull()) + + /** Alias for calling [body] with `Body.ofDataSyncAll(dataSyncAll)`. */ + fun body(dataSyncAll: Body.DataSyncAll) = body(Body.ofDataSyncAll(dataSyncAll)) + + /** Alias for calling [body] with `Body.ofW4FormEmployeeSync(w4FormEmployeeSync)`. */ + fun body(w4FormEmployeeSync: Body.W4FormEmployeeSync) = + body(Body.ofW4FormEmployeeSync(w4FormEmployeeSync)) + + /** + * Alias for calling [body] with the following: + * ```java + * Body.W4FormEmployeeSync.builder() + * .type(JobAutomatedCreateParams.Body.W4FormEmployeeSync.Type.W4_FORM_EMPLOYEE_SYNC) + * .params(params) + * .build() + * ``` + */ + fun w4FormEmployeeSyncBody(params: Body.W4FormEmployeeSync.Params) = + body( + Body.W4FormEmployeeSync.builder() + .type( + JobAutomatedCreateParams.Body.W4FormEmployeeSync.Type.W4_FORM_EMPLOYEE_SYNC + ) + .params(params) + .build() + ) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [JobAutomatedCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): JobAutomatedCreateParams = + JobAutomatedCreateParams(body, additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _body(): Optional = Optional.ofNullable(body) override fun _headers(): Headers = additionalHeaders @@ -92,13 +252,12 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { + fun accept(visitor: Visitor): T = + when { dataSyncAll != null -> visitor.visitDataSyncAll(dataSyncAll) w4FormEmployeeSync != null -> visitor.visitW4FormEmployeeSync(w4FormEmployeeSync) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -121,6 +280,33 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitDataSyncAll(dataSyncAll: DataSyncAll) = dataSyncAll.validity() + + override fun visitW4FormEmployeeSync(w4FormEmployeeSync: W4FormEmployeeSync) = + w4FormEmployeeSync.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -177,16 +363,14 @@ private constructor( when (type) { "data_sync_all" -> { - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Body(dataSyncAll = it, _json = json) - } + return tryDeserialize(node, jacksonTypeRef())?.let { + Body(dataSyncAll = it, _json = json) + } ?: Body(_json = json) } "w4_form_employee_sync" -> { - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Body(w4FormEmployeeSync = it, _json = json) - } + return tryDeserialize(node, jacksonTypeRef())?.let { + Body(w4FormEmployeeSync = it, _json = json) + } ?: Body(_json = json) } } @@ -211,42 +395,55 @@ private constructor( } } - @NoAutoDetect class DataSyncAll - @JsonCreator private constructor( - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The type of job to start. */ + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * The type of job to start. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ fun type(): Type = type.getRequired("type") - /** The type of job to start. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): DataSyncAll = apply { - if (validated) { - return@apply - } - - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [DataSyncAll]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -265,7 +462,13 @@ private constructor( /** The type of job to start. */ fun type(type: Type) = type(JsonField.of(type)) - /** The type of job to start. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -290,10 +493,50 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [DataSyncAll]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): DataSyncAll = - DataSyncAll(checkRequired("type", type), additionalProperties.toImmutable()) + DataSyncAll(checkRequired("type", type), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): DataSyncAll = apply { + if (validated) { + return@apply + } + + type().validate() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (type.asKnown().getOrNull()?.validity() ?: 0) + /** The type of job to start. */ class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -379,6 +622,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -410,50 +680,74 @@ private constructor( "DataSyncAll{type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class W4FormEmployeeSync - @JsonCreator private constructor( - @JsonProperty("params") - @ExcludeMissing - private val params: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val params: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("params") + @ExcludeMissing + params: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(params, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ fun params(): Params = params.getRequired("params") - /** The type of job to start. */ + /** + * The type of job to start. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ fun type(): Type = type.getRequired("type") + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params - /** The type of job to start. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): W4FormEmployeeSync = apply { - if (validated) { - return@apply - } - - params().validate() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [W4FormEmployeeSync]. + * + * The following fields are required: + * ```java + * .params() + * .type() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -473,12 +767,25 @@ private constructor( fun params(params: Params) = params(JsonField.of(params)) + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun params(params: JsonField) = apply { this.params = params } /** The type of job to start. */ fun type(type: Type) = type(JsonField.of(type)) - /** The type of job to start. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -503,52 +810,112 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [W4FormEmployeeSync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .params() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): W4FormEmployeeSync = W4FormEmployeeSync( checkRequired("params", params), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): W4FormEmployeeSync = apply { + if (validated) { + return@apply + } + + params().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (params.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Params - @JsonCreator private constructor( - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val individualId: JsonField, + private val additionalProperties: MutableMap, ) { - /** The unique ID of the individual for W-4 data sync. */ + @JsonCreator + private constructor( + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of() + ) : this(individualId, mutableMapOf()) + + /** + * The unique ID of the individual for W-4 data sync. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected + * value). + */ fun individualId(): String = individualId.getRequired("individual_id") - /** The unique ID of the individual for W-4 data sync. */ + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Params = apply { - if (validated) { - return@apply - } - - individualId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Params]. + * + * The following fields are required: + * ```java + * .individualId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -568,7 +935,13 @@ private constructor( fun individualId(individualId: String) = individualId(JsonField.of(individualId)) - /** The unique ID of the individual for W-4 data sync. */ + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -595,13 +968,53 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Params]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .individualId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Params = Params( checkRequired("individualId", individualId), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + individualId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (individualId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -705,6 +1118,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -737,151 +1177,6 @@ private constructor( } } - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun none(): JobAutomatedCreateParams = builder().build() - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [JobAutomatedCreateParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var body: Body? = null - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - - @JvmSynthetic - internal fun from(jobAutomatedCreateParams: JobAutomatedCreateParams) = apply { - body = jobAutomatedCreateParams.body - additionalHeaders = jobAutomatedCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = jobAutomatedCreateParams.additionalQueryParams.toBuilder() - } - - fun body(body: Body?) = apply { this.body = body } - - fun body(body: Optional) = body(body.orElse(null)) - - fun body(dataSyncAll: Body.DataSyncAll) = body(Body.ofDataSyncAll(dataSyncAll)) - - fun body(w4FormEmployeeSync: Body.W4FormEmployeeSync) = - body(Body.ofW4FormEmployeeSync(w4FormEmployeeSync)) - - fun w4FormEmployeeSyncBody(params: Body.W4FormEmployeeSync.Params) = - body( - Body.W4FormEmployeeSync.builder() - .type( - JobAutomatedCreateParams.Body.W4FormEmployeeSync.Type.W4_FORM_EMPLOYEE_SYNC - ) - .params(params) - .build() - ) - - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } - - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } - - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } - - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } - - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } - - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } - - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } - - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } - - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } - - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } - - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } - - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } - - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } - - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } - - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } - - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } - - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } - - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } - - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } - - fun build(): JobAutomatedCreateParams = - JobAutomatedCreateParams(body, additionalHeaders.build(), additionalQueryParams.build()) - } - override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedListPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedListPage.kt deleted file mode 100644 index 3774d28b..00000000 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedListPage.kt +++ /dev/null @@ -1,195 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.tryfinch.api.models - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.tryfinch.api.core.ExcludeMissing -import com.tryfinch.api.core.JsonField -import com.tryfinch.api.core.JsonMissing -import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable -import com.tryfinch.api.services.blocking.jobs.AutomatedService -import java.util.Objects -import java.util.Optional -import java.util.stream.Stream -import java.util.stream.StreamSupport - -/** - * Get all automated jobs. Automated jobs are completed by a machine. By default, jobs are sorted in - * descending order by submission time. For scheduled jobs such as data syncs, only the next - * scheduled job is shown. - */ -class JobAutomatedListPage -private constructor( - private val automatedService: AutomatedService, - private val params: JobAutomatedListParams, - private val response: Response, -) { - - fun response(): Response = response - - fun data(): List = response().data() - - fun paging(): Optional = response().paging() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is JobAutomatedListPage && automatedService == other.automatedService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(automatedService, params, response) /* spotless:on */ - - override fun toString() = - "JobAutomatedListPage{automatedService=$automatedService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (data().isEmpty()) { - return false - } - - return paging().flatMap { it.offset() }.orElse(0) + data().count() < - paging().flatMap { it.count() }.orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - JobAutomatedListParams.builder() - .from(params) - .offset(paging().flatMap { it.offset() }.orElse(0) + data().count()) - .build() - ) - } - - fun getNextPage(): Optional { - return getNextPageParams().map { automatedService.list(it) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of( - automatedService: AutomatedService, - params: JobAutomatedListParams, - response: Response, - ) = JobAutomatedListPage(automatedService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("data") - private val data: JsonField> = JsonMissing.of(), - @JsonProperty("paging") private val paging: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun data(): List = data.getNullable("data") ?: listOf() - - fun paging(): Optional = Optional.ofNullable(paging.getNullable("paging")) - - @JsonProperty("data") - fun _data(): Optional>> = Optional.ofNullable(data) - - @JsonProperty("paging") - fun _paging(): Optional> = Optional.ofNullable(paging) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - data().map { it.validate() } - paging().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && data == other.data && paging == other.paging && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(data, paging, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{data=$data, paging=$paging, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var data: JsonField> = JsonMissing.of() - private var paging: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.data = page.data - this.paging = page.paging - this.additionalProperties.putAll(page.additionalProperties) - } - - fun data(data: List) = data(JsonField.of(data)) - - fun data(data: JsonField>) = apply { this.data = data } - - fun paging(paging: Paging) = paging(JsonField.of(paging)) - - fun paging(paging: JsonField) = apply { this.paging = paging } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(data, paging, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: JobAutomatedListPage) : Iterable { - - override fun iterator(): Iterator = iterator { - var page = firstPage - var index = 0 - while (true) { - while (index < page.data().size) { - yield(page.data()[index++]) - } - page = page.getNextPage().orElse(null) ?: break - index = 0 - } - } - - fun stream(): Stream { - return StreamSupport.stream(spliterator(), false) - } - } -} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedListPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedListPageAsync.kt deleted file mode 100644 index f2ba3f01..00000000 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedListPageAsync.kt +++ /dev/null @@ -1,208 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.tryfinch.api.models - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.tryfinch.api.core.ExcludeMissing -import com.tryfinch.api.core.JsonField -import com.tryfinch.api.core.JsonMissing -import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable -import com.tryfinch.api.services.async.jobs.AutomatedServiceAsync -import java.util.Objects -import java.util.Optional -import java.util.concurrent.CompletableFuture -import java.util.concurrent.Executor -import java.util.function.Predicate - -/** - * Get all automated jobs. Automated jobs are completed by a machine. By default, jobs are sorted in - * descending order by submission time. For scheduled jobs such as data syncs, only the next - * scheduled job is shown. - */ -class JobAutomatedListPageAsync -private constructor( - private val automatedService: AutomatedServiceAsync, - private val params: JobAutomatedListParams, - private val response: Response, -) { - - fun response(): Response = response - - fun data(): List = response().data() - - fun paging(): Optional = response().paging() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is JobAutomatedListPageAsync && automatedService == other.automatedService && params == other.params && response == other.response /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(automatedService, params, response) /* spotless:on */ - - override fun toString() = - "JobAutomatedListPageAsync{automatedService=$automatedService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - if (data().isEmpty()) { - return false - } - - return paging().flatMap { it.offset() }.orElse(0) + data().count() < - paging().flatMap { it.count() }.orElse(Long.MAX_VALUE) - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } - - return Optional.of( - JobAutomatedListParams.builder() - .from(params) - .offset(paging().flatMap { it.offset() }.orElse(0) + data().count()) - .build() - ) - } - - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { automatedService.list(it).thenApply { Optional.of(it) } } - .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of( - automatedService: AutomatedServiceAsync, - params: JobAutomatedListParams, - response: Response, - ) = JobAutomatedListPageAsync(automatedService, params, response) - } - - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("data") - private val data: JsonField> = JsonMissing.of(), - @JsonProperty("paging") private val paging: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun data(): List = data.getNullable("data") ?: listOf() - - fun paging(): Optional = Optional.ofNullable(paging.getNullable("paging")) - - @JsonProperty("data") - fun _data(): Optional>> = Optional.ofNullable(data) - - @JsonProperty("paging") - fun _paging(): Optional> = Optional.ofNullable(paging) - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Response = apply { - if (validated) { - return@apply - } - - data().map { it.validate() } - paging().ifPresent { it.validate() } - validated = true - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Response && data == other.data && paging == other.paging && additionalProperties == other.additionalProperties /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(data, paging, additionalProperties) /* spotless:on */ - - override fun toString() = - "Response{data=$data, paging=$paging, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var data: JsonField> = JsonMissing.of() - private var paging: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(page: Response) = apply { - this.data = page.data - this.paging = page.paging - this.additionalProperties.putAll(page.additionalProperties) - } - - fun data(data: List) = data(JsonField.of(data)) - - fun data(data: JsonField>) = apply { this.data = data } - - fun paging(paging: Paging) = paging(JsonField.of(paging)) - - fun paging(paging: JsonField) = apply { this.paging = paging } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(data, paging, additionalProperties.toImmutable()) - } - } - - class AutoPager(private val firstPage: JobAutomatedListPageAsync) { - - fun forEach( - action: Predicate, - executor: Executor, - ): CompletableFuture { - fun CompletableFuture>.forEach( - action: (AutomatedAsyncJob) -> Boolean, - executor: Executor, - ): CompletableFuture = - thenComposeAsync( - { page -> - page - .filter { it.data().all(action) } - .map { it.getNextPage().forEach(action, executor) } - .orElseGet { CompletableFuture.completedFuture(null) } - }, - executor, - ) - return CompletableFuture.completedFuture(Optional.of(firstPage)) - .forEach(action::test, executor) - } - - fun toList(executor: Executor): CompletableFuture> { - val values = mutableListOf() - return forEach(values::add, executor).thenApply { values } - } - } -} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedListParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedListParams.kt index d49551f0..bcd9259d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedListParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedListParams.kt @@ -2,12 +2,12 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** * Get all automated jobs. Automated jobs are completed by a machine. By default, jobs are sorted in @@ -32,27 +32,17 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.limit?.let { queryParams.put("limit", listOf(it.toString())) } - this.offset?.let { queryParams.put("offset", listOf(it.toString())) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): JobAutomatedListParams = builder().build() + /** Returns a mutable builder for constructing an instance of [JobAutomatedListParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [JobAutomatedListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var limit: Long? = null @@ -71,22 +61,28 @@ private constructor( /** Number of items to return */ fun limit(limit: Long?) = apply { this.limit = limit } - /** Number of items to return */ + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun limit(limit: Long) = limit(limit as Long?) - /** Number of items to return */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun limit(limit: Optional) = limit(limit.orElse(null) as Long?) + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** Index to start from (defaults to 0) */ fun offset(offset: Long?) = apply { this.offset = offset } - /** Index to start from (defaults to 0) */ + /** + * Alias for [Builder.offset]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun offset(offset: Long) = offset(offset as Long?) - /** Index to start from (defaults to 0) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun offset(offset: Optional) = offset(offset.orElse(null) as Long?) + /** Alias for calling [Builder.offset] with `offset.orElse(null)`. */ + fun offset(offset: Optional) = offset(offset.getOrNull()) fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -186,6 +182,11 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [JobAutomatedListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): JobAutomatedListParams = JobAutomatedListParams( limit, @@ -195,6 +196,17 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + limit?.let { put("limit", it.toString()) } + offset?.let { put("offset", it.toString()) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedRetrieveParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedRetrieveParams.kt index 8f9419ca..ac519b49 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedRetrieveParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobAutomatedRetrieveParams.kt @@ -2,7 +2,6 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers @@ -23,26 +22,22 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> jobId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [JobAutomatedRetrieveParams]. + * + * The following fields are required: + * ```java + * .jobId() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [JobAutomatedRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var jobId: String? = null @@ -156,6 +151,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [JobAutomatedRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .jobId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): JobAutomatedRetrieveParams = JobAutomatedRetrieveParams( checkRequired("jobId", jobId), @@ -164,6 +171,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> jobId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobCompletionEvent.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobCompletionEvent.kt index 59f91f23..a8ee4168 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobCompletionEvent.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobCompletionEvent.kt @@ -11,57 +11,85 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class JobCompletionEvent -@JsonCreator private constructor( - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("data") @ExcludeMissing private val data: JsonField = JsonMissing.of(), - @JsonProperty("event_type") - @ExcludeMissing - private val eventType: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accountId: JsonField, + private val companyId: JsonField, + private val connectionId: JsonField, + private val data: JsonField, + private val eventType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("event_type") + @ExcludeMissing + eventType: JsonField = JsonMissing.of(), + ) : this(accountId, companyId, connectionId, data, eventType, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder() + .accountId(accountId) + .companyId(companyId) + .connectionId(connectionId) + .build() + /** * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") /** * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") - /** Unique Finch ID of the connection associated with the webhook event. */ - fun connectionId(): Optional = - Optional.ofNullable(connectionId.getNullable("connection_id")) + /** + * Unique Finch ID of the connection associated with the webhook event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun connectionId(): Optional = connectionId.getOptional("connection_id") - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") - fun eventType(): Optional = Optional.ofNullable(eventType.getNullable("event_type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun eventType(): Optional = eventType.getOptional("event_type") /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("account_id") @@ -69,53 +97,61 @@ private constructor( fun _accountId(): JsonField = accountId /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [eventType]. + * + * Unlike [eventType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("event_type") @ExcludeMissing fun _eventType(): JsonField = eventType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBaseWebhookEvent(): BaseWebhookEvent = - BaseWebhookEvent.builder() - .accountId(accountId) - .companyId(companyId) - .connectionId(connectionId) - .build() - - private var validated: Boolean = false - - fun validate(): JobCompletionEvent = apply { - if (validated) { - return@apply - } - - accountId() - companyId() - connectionId() - data().ifPresent { it.validate() } - eventType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [JobCompletionEvent]. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -147,8 +183,11 @@ private constructor( fun accountId(accountId: String) = accountId(JsonField.of(accountId)) /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } @@ -161,8 +200,11 @@ private constructor( fun companyId(companyId: String) = companyId(JsonField.of(companyId)) /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } @@ -170,17 +212,36 @@ private constructor( /** Unique Finch ID of the connection associated with the webhook event. */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } fun data(data: Data) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun eventType(eventType: EventType) = eventType(JsonField.of(eventType)) + /** + * Sets [Builder.eventType] to an arbitrary JSON value. + * + * You should usually call [Builder.eventType] with a well-typed [EventType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun eventType(eventType: JsonField) = apply { this.eventType = eventType } fun additionalProperties(additionalProperties: Map) = apply { @@ -202,6 +263,19 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [JobCompletionEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): JobCompletionEvent = JobCompletionEvent( checkRequired("accountId", accountId), @@ -209,56 +283,112 @@ private constructor( connectionId, data, eventType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): JobCompletionEvent = apply { + if (validated) { + return@apply + } + + accountId() + companyId() + connectionId() + data().ifPresent { it.validate() } + eventType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountId.asKnown().isPresent) 1 else 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (eventType.asKnown().getOrNull()?.validity() ?: 0) + class Data - @JsonCreator private constructor( - @JsonProperty("job_id") - @ExcludeMissing - private val jobId: JsonField = JsonMissing.of(), - @JsonProperty("job_url") - @ExcludeMissing - private val jobUrl: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val jobId: JsonField, + private val jobUrl: JsonField, + private val additionalProperties: MutableMap, ) { - /** The id of the job which has completed. */ + @JsonCreator + private constructor( + @JsonProperty("job_id") @ExcludeMissing jobId: JsonField = JsonMissing.of(), + @JsonProperty("job_url") @ExcludeMissing jobUrl: JsonField = JsonMissing.of(), + ) : this(jobId, jobUrl, mutableMapOf()) + + /** + * The id of the job which has completed. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ fun jobId(): String = jobId.getRequired("job_id") - /** The url to query the result of the job. */ + /** + * The url to query the result of the job. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ fun jobUrl(): String = jobUrl.getRequired("job_url") - /** The id of the job which has completed. */ + /** + * Returns the raw JSON value of [jobId]. + * + * Unlike [jobId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("job_id") @ExcludeMissing fun _jobId(): JsonField = jobId - /** The url to query the result of the job. */ + /** + * Returns the raw JSON value of [jobUrl]. + * + * Unlike [jobUrl], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("job_url") @ExcludeMissing fun _jobUrl(): JsonField = jobUrl + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Data = apply { - if (validated) { - return@apply - } - - jobId() - jobUrl() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Data]. + * + * The following fields are required: + * ```java + * .jobId() + * .jobUrl() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -279,13 +409,25 @@ private constructor( /** The id of the job which has completed. */ fun jobId(jobId: String) = jobId(JsonField.of(jobId)) - /** The id of the job which has completed. */ + /** + * Sets [Builder.jobId] to an arbitrary JSON value. + * + * You should usually call [Builder.jobId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun jobId(jobId: JsonField) = apply { this.jobId = jobId } /** The url to query the result of the job. */ fun jobUrl(jobUrl: String) = jobUrl(JsonField.of(jobUrl)) - /** The url to query the result of the job. */ + /** + * Sets [Builder.jobUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.jobUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun jobUrl(jobUrl: JsonField) = apply { this.jobUrl = jobUrl } fun additionalProperties(additionalProperties: Map) = apply { @@ -307,14 +449,57 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .jobId() + * .jobUrl() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Data = Data( checkRequired("jobId", jobId), checkRequired("jobUrl", jobUrl), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + jobId() + jobUrl() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (jobId.asKnown().isPresent) 1 else 0) + (if (jobUrl.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -443,6 +628,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EventType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobCreateResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobCreateResponse.kt index b5f0299c..0899bd84 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobCreateResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobCreateResponse.kt @@ -10,79 +10,123 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects -@NoAutoDetect class JobCreateResponse -@JsonCreator private constructor( - @JsonProperty("allowed_refreshes") - @ExcludeMissing - private val allowedRefreshes: JsonField = JsonMissing.of(), - @JsonProperty("job_id") @ExcludeMissing private val jobId: JsonField = JsonMissing.of(), - @JsonProperty("job_url") - @ExcludeMissing - private val jobUrl: JsonField = JsonMissing.of(), - @JsonProperty("remaining_refreshes") - @ExcludeMissing - private val remainingRefreshes: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val allowedRefreshes: JsonField, + private val jobId: JsonField, + private val jobUrl: JsonField, + private val remainingRefreshes: JsonField, + private val additionalProperties: MutableMap, ) { - /** The number of allowed refreshes per hour (per hour, fixed window) */ + @JsonCreator + private constructor( + @JsonProperty("allowed_refreshes") + @ExcludeMissing + allowedRefreshes: JsonField = JsonMissing.of(), + @JsonProperty("job_id") @ExcludeMissing jobId: JsonField = JsonMissing.of(), + @JsonProperty("job_url") @ExcludeMissing jobUrl: JsonField = JsonMissing.of(), + @JsonProperty("remaining_refreshes") + @ExcludeMissing + remainingRefreshes: JsonField = JsonMissing.of(), + ) : this(allowedRefreshes, jobId, jobUrl, remainingRefreshes, mutableMapOf()) + + /** + * The number of allowed refreshes per hour (per hour, fixed window) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun allowedRefreshes(): Long = allowedRefreshes.getRequired("allowed_refreshes") - /** The id of the job that has been created. */ + /** + * The id of the job that has been created. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun jobId(): String = jobId.getRequired("job_id") - /** The url that can be used to retrieve the job status */ + /** + * The url that can be used to retrieve the job status + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun jobUrl(): String = jobUrl.getRequired("job_url") - /** The number of remaining refreshes available (per hour, fixed window) */ + /** + * The number of remaining refreshes available (per hour, fixed window) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun remainingRefreshes(): Long = remainingRefreshes.getRequired("remaining_refreshes") - /** The number of allowed refreshes per hour (per hour, fixed window) */ + /** + * Returns the raw JSON value of [allowedRefreshes]. + * + * Unlike [allowedRefreshes], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("allowed_refreshes") @ExcludeMissing fun _allowedRefreshes(): JsonField = allowedRefreshes - /** The id of the job that has been created. */ + /** + * Returns the raw JSON value of [jobId]. + * + * Unlike [jobId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("job_id") @ExcludeMissing fun _jobId(): JsonField = jobId - /** The url that can be used to retrieve the job status */ + /** + * Returns the raw JSON value of [jobUrl]. + * + * Unlike [jobUrl], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("job_url") @ExcludeMissing fun _jobUrl(): JsonField = jobUrl - /** The number of remaining refreshes available (per hour, fixed window) */ + /** + * Returns the raw JSON value of [remainingRefreshes]. + * + * Unlike [remainingRefreshes], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("remaining_refreshes") @ExcludeMissing fun _remainingRefreshes(): JsonField = remainingRefreshes + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): JobCreateResponse = apply { - if (validated) { - return@apply - } - - allowedRefreshes() - jobId() - jobUrl() - remainingRefreshes() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [JobCreateResponse]. + * + * The following fields are required: + * ```java + * .allowedRefreshes() + * .jobId() + * .jobUrl() + * .remainingRefreshes() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -108,7 +152,13 @@ private constructor( fun allowedRefreshes(allowedRefreshes: Long) = allowedRefreshes(JsonField.of(allowedRefreshes)) - /** The number of allowed refreshes per hour (per hour, fixed window) */ + /** + * Sets [Builder.allowedRefreshes] to an arbitrary JSON value. + * + * You should usually call [Builder.allowedRefreshes] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun allowedRefreshes(allowedRefreshes: JsonField) = apply { this.allowedRefreshes = allowedRefreshes } @@ -116,20 +166,36 @@ private constructor( /** The id of the job that has been created. */ fun jobId(jobId: String) = jobId(JsonField.of(jobId)) - /** The id of the job that has been created. */ + /** + * Sets [Builder.jobId] to an arbitrary JSON value. + * + * You should usually call [Builder.jobId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun jobId(jobId: JsonField) = apply { this.jobId = jobId } /** The url that can be used to retrieve the job status */ fun jobUrl(jobUrl: String) = jobUrl(JsonField.of(jobUrl)) - /** The url that can be used to retrieve the job status */ + /** + * Sets [Builder.jobUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.jobUrl] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun jobUrl(jobUrl: JsonField) = apply { this.jobUrl = jobUrl } /** The number of remaining refreshes available (per hour, fixed window) */ fun remainingRefreshes(remainingRefreshes: Long) = remainingRefreshes(JsonField.of(remainingRefreshes)) - /** The number of remaining refreshes available (per hour, fixed window) */ + /** + * Sets [Builder.remainingRefreshes] to an arbitrary JSON value. + * + * You should usually call [Builder.remainingRefreshes] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun remainingRefreshes(remainingRefreshes: JsonField) = apply { this.remainingRefreshes = remainingRefreshes } @@ -153,16 +219,65 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [JobCreateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .allowedRefreshes() + * .jobId() + * .jobUrl() + * .remainingRefreshes() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): JobCreateResponse = JobCreateResponse( checkRequired("allowedRefreshes", allowedRefreshes), checkRequired("jobId", jobId), checkRequired("jobUrl", jobUrl), checkRequired("remainingRefreshes", remainingRefreshes), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): JobCreateResponse = apply { + if (validated) { + return@apply + } + + allowedRefreshes() + jobId() + jobUrl() + remainingRefreshes() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (allowedRefreshes.asKnown().isPresent) 1 else 0) + + (if (jobId.asKnown().isPresent) 1 else 0) + + (if (jobUrl.asKnown().isPresent) 1 else 0) + + (if (remainingRefreshes.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobManualRetrieveParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobManualRetrieveParams.kt index 32fc6bca..a1833b8c 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobManualRetrieveParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/JobManualRetrieveParams.kt @@ -2,7 +2,6 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers @@ -26,26 +25,22 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> jobId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [JobManualRetrieveParams]. + * + * The following fields are required: + * ```java + * .jobId() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [JobManualRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var jobId: String? = null @@ -159,6 +154,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [JobManualRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .jobId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): JobManualRetrieveParams = JobManualRetrieveParams( checkRequired("jobId", jobId), @@ -167,6 +174,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> jobId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Location.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Location.kt index 20ce723d..5af14dcb 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Location.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Location.kt @@ -10,103 +10,170 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class Location -@JsonCreator private constructor( - @JsonProperty("city") @ExcludeMissing private val city: JsonField = JsonMissing.of(), - @JsonProperty("country") - @ExcludeMissing - private val country: JsonField = JsonMissing.of(), - @JsonProperty("line1") @ExcludeMissing private val line1: JsonField = JsonMissing.of(), - @JsonProperty("line2") @ExcludeMissing private val line2: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("postal_code") - @ExcludeMissing - private val postalCode: JsonField = JsonMissing.of(), - @JsonProperty("source_id") - @ExcludeMissing - private val sourceId: JsonField = JsonMissing.of(), - @JsonProperty("state") @ExcludeMissing private val state: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val city: JsonField, + private val country: JsonField, + private val line1: JsonField, + private val line2: JsonField, + private val name: JsonField, + private val postalCode: JsonField, + private val sourceId: JsonField, + private val state: JsonField, + private val additionalProperties: MutableMap, ) { - /** City, district, suburb, town, or village. */ - fun city(): Optional = Optional.ofNullable(city.getNullable("city")) - - /** The 2-letter ISO 3166 country code. */ - fun country(): Optional = Optional.ofNullable(country.getNullable("country")) - - /** Street address or PO box. */ - fun line1(): Optional = Optional.ofNullable(line1.getNullable("line1")) - - /** Apartment, suite, unit, or building. */ - fun line2(): Optional = Optional.ofNullable(line2.getNullable("line2")) - - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** The postal code or zip code. */ - fun postalCode(): Optional = Optional.ofNullable(postalCode.getNullable("postal_code")) - - fun sourceId(): Optional = Optional.ofNullable(sourceId.getNullable("source_id")) - - /** The state code. */ - fun state(): Optional = Optional.ofNullable(state.getNullable("state")) - - /** City, district, suburb, town, or village. */ + @JsonCreator + private constructor( + @JsonProperty("city") @ExcludeMissing city: JsonField = JsonMissing.of(), + @JsonProperty("country") @ExcludeMissing country: JsonField = JsonMissing.of(), + @JsonProperty("line1") @ExcludeMissing line1: JsonField = JsonMissing.of(), + @JsonProperty("line2") @ExcludeMissing line2: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("postal_code") + @ExcludeMissing + postalCode: JsonField = JsonMissing.of(), + @JsonProperty("source_id") @ExcludeMissing sourceId: JsonField = JsonMissing.of(), + @JsonProperty("state") @ExcludeMissing state: JsonField = JsonMissing.of(), + ) : this(city, country, line1, line2, name, postalCode, sourceId, state, mutableMapOf()) + + /** + * City, district, suburb, town, or village. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun city(): Optional = city.getOptional("city") + + /** + * The 2-letter ISO 3166 country code. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun country(): Optional = country.getOptional("country") + + /** + * Street address or PO box. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun line1(): Optional = line1.getOptional("line1") + + /** + * Apartment, suite, unit, or building. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun line2(): Optional = line2.getOptional("line2") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * The postal code or zip code. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun postalCode(): Optional = postalCode.getOptional("postal_code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun sourceId(): Optional = sourceId.getOptional("source_id") + + /** + * The state code. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun state(): Optional = state.getOptional("state") + + /** + * Returns the raw JSON value of [city]. + * + * Unlike [city], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("city") @ExcludeMissing fun _city(): JsonField = city - /** The 2-letter ISO 3166 country code. */ + /** + * Returns the raw JSON value of [country]. + * + * Unlike [country], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("country") @ExcludeMissing fun _country(): JsonField = country - /** Street address or PO box. */ + /** + * Returns the raw JSON value of [line1]. + * + * Unlike [line1], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("line1") @ExcludeMissing fun _line1(): JsonField = line1 - /** Apartment, suite, unit, or building. */ + /** + * Returns the raw JSON value of [line2]. + * + * Unlike [line2], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("line2") @ExcludeMissing fun _line2(): JsonField = line2 + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** The postal code or zip code. */ + /** + * Returns the raw JSON value of [postalCode]. + * + * Unlike [postalCode], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("postal_code") @ExcludeMissing fun _postalCode(): JsonField = postalCode + /** + * Returns the raw JSON value of [sourceId]. + * + * Unlike [sourceId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("source_id") @ExcludeMissing fun _sourceId(): JsonField = sourceId - /** The state code. */ + /** + * Returns the raw JSON value of [state]. + * + * Unlike [state], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("state") @ExcludeMissing fun _state(): JsonField = state + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Location = apply { - if (validated) { - return@apply - } - - city() - country() - line1() - line2() - name() - postalCode() - sourceId() - state() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Location]. */ @JvmStatic fun builder() = Builder() } @@ -139,67 +206,112 @@ private constructor( /** City, district, suburb, town, or village. */ fun city(city: String?) = city(JsonField.ofNullable(city)) - /** City, district, suburb, town, or village. */ - fun city(city: Optional) = city(city.orElse(null)) + /** Alias for calling [Builder.city] with `city.orElse(null)`. */ + fun city(city: Optional) = city(city.getOrNull()) - /** City, district, suburb, town, or village. */ + /** + * Sets [Builder.city] to an arbitrary JSON value. + * + * You should usually call [Builder.city] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun city(city: JsonField) = apply { this.city = city } /** The 2-letter ISO 3166 country code. */ fun country(country: String?) = country(JsonField.ofNullable(country)) - /** The 2-letter ISO 3166 country code. */ - fun country(country: Optional) = country(country.orElse(null)) + /** Alias for calling [Builder.country] with `country.orElse(null)`. */ + fun country(country: Optional) = country(country.getOrNull()) - /** The 2-letter ISO 3166 country code. */ + /** + * Sets [Builder.country] to an arbitrary JSON value. + * + * You should usually call [Builder.country] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun country(country: JsonField) = apply { this.country = country } /** Street address or PO box. */ fun line1(line1: String?) = line1(JsonField.ofNullable(line1)) - /** Street address or PO box. */ - fun line1(line1: Optional) = line1(line1.orElse(null)) + /** Alias for calling [Builder.line1] with `line1.orElse(null)`. */ + fun line1(line1: Optional) = line1(line1.getOrNull()) - /** Street address or PO box. */ + /** + * Sets [Builder.line1] to an arbitrary JSON value. + * + * You should usually call [Builder.line1] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun line1(line1: JsonField) = apply { this.line1 = line1 } /** Apartment, suite, unit, or building. */ fun line2(line2: String?) = line2(JsonField.ofNullable(line2)) - /** Apartment, suite, unit, or building. */ - fun line2(line2: Optional) = line2(line2.orElse(null)) + /** Alias for calling [Builder.line2] with `line2.orElse(null)`. */ + fun line2(line2: Optional) = line2(line2.getOrNull()) - /** Apartment, suite, unit, or building. */ + /** + * Sets [Builder.line2] to an arbitrary JSON value. + * + * You should usually call [Builder.line2] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun line2(line2: JsonField) = apply { this.line2 = line2 } fun name(name: String?) = name(JsonField.ofNullable(name)) - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } /** The postal code or zip code. */ fun postalCode(postalCode: String?) = postalCode(JsonField.ofNullable(postalCode)) - /** The postal code or zip code. */ - fun postalCode(postalCode: Optional) = postalCode(postalCode.orElse(null)) + /** Alias for calling [Builder.postalCode] with `postalCode.orElse(null)`. */ + fun postalCode(postalCode: Optional) = postalCode(postalCode.getOrNull()) - /** The postal code or zip code. */ + /** + * Sets [Builder.postalCode] to an arbitrary JSON value. + * + * You should usually call [Builder.postalCode] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun postalCode(postalCode: JsonField) = apply { this.postalCode = postalCode } fun sourceId(sourceId: String?) = sourceId(JsonField.ofNullable(sourceId)) - fun sourceId(sourceId: Optional) = sourceId(sourceId.orElse(null)) + /** Alias for calling [Builder.sourceId] with `sourceId.orElse(null)`. */ + fun sourceId(sourceId: Optional) = sourceId(sourceId.getOrNull()) + /** + * Sets [Builder.sourceId] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun sourceId(sourceId: JsonField) = apply { this.sourceId = sourceId } /** The state code. */ fun state(state: String?) = state(JsonField.ofNullable(state)) - /** The state code. */ - fun state(state: Optional) = state(state.orElse(null)) + /** Alias for calling [Builder.state] with `state.orElse(null)`. */ + fun state(state: Optional) = state(state.getOrNull()) - /** The state code. */ + /** + * Sets [Builder.state] to an arbitrary JSON value. + * + * You should usually call [Builder.state] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun state(state: JsonField) = apply { this.state = state } fun additionalProperties(additionalProperties: Map) = apply { @@ -221,6 +333,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Location]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Location = Location( city, @@ -231,10 +348,52 @@ private constructor( postalCode, sourceId, state, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Location = apply { + if (validated) { + return@apply + } + + city() + country() + line1() + line2() + name() + postalCode() + sourceId() + state() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (city.asKnown().isPresent) 1 else 0) + + (if (country.asKnown().isPresent) 1 else 0) + + (if (line1.asKnown().isPresent) 1 else 0) + + (if (line2.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (postalCode.asKnown().isPresent) 1 else 0) + + (if (sourceId.asKnown().isPresent) 1 else 0) + + (if (state.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ManualAsyncJob.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ManualAsyncJob.kt index ded94816..d76f84e3 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ManualAsyncJob.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ManualAsyncJob.kt @@ -11,63 +11,95 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class ManualAsyncJob -@JsonCreator private constructor( - @JsonProperty("body") - @ExcludeMissing - private val body: JsonField> = JsonMissing.of(), - @JsonProperty("job_id") @ExcludeMissing private val jobId: JsonField = JsonMissing.of(), - @JsonProperty("status") - @ExcludeMissing - private val status: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val body: JsonField>, + private val jobId: JsonField, + private val status: JsonField, + private val additionalProperties: MutableMap, ) { - /** Specific information about the job, such as individual statuses for batch jobs. */ - fun body(): Optional> = Optional.ofNullable(body.getNullable("body")) - + @JsonCreator + private constructor( + @JsonProperty("body") @ExcludeMissing body: JsonField> = JsonMissing.of(), + @JsonProperty("job_id") @ExcludeMissing jobId: JsonField = JsonMissing.of(), + @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), + ) : this(body, jobId, status, mutableMapOf()) + + /** + * Specific information about the job, such as individual statuses for batch jobs. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun body(): Optional> = body.getOptional("body") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun jobId(): String = jobId.getRequired("job_id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun status(): Status = status.getRequired("status") - /** Specific information about the job, such as individual statuses for batch jobs. */ + /** + * Returns the raw JSON value of [body]. + * + * Unlike [body], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("body") @ExcludeMissing fun _body(): JsonField> = body + /** + * Returns the raw JSON value of [jobId]. + * + * Unlike [jobId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("job_id") @ExcludeMissing fun _jobId(): JsonField = jobId + /** + * Returns the raw JSON value of [status]. + * + * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): ManualAsyncJob = apply { - if (validated) { - return@apply - } - - body() - jobId() - status() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [ManualAsyncJob]. + * + * The following fields are required: + * ```java + * .body() + * .jobId() + * .status() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -90,34 +122,50 @@ private constructor( /** Specific information about the job, such as individual statuses for batch jobs. */ fun body(body: List?) = body(JsonField.ofNullable(body)) - /** Specific information about the job, such as individual statuses for batch jobs. */ - fun body(body: Optional>) = body(body.orElse(null)) + /** Alias for calling [Builder.body] with `body.orElse(null)`. */ + fun body(body: Optional>) = body(body.getOrNull()) - /** Specific information about the job, such as individual statuses for batch jobs. */ + /** + * Sets [Builder.body] to an arbitrary JSON value. + * + * You should usually call [Builder.body] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun body(body: JsonField>) = apply { this.body = body.map { it.toMutableList() } } - /** Specific information about the job, such as individual statuses for batch jobs. */ + /** + * Adds a single [JsonValue] to [Builder.body]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addBody(body: JsonValue) = apply { this.body = - (this.body ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(body) + (this.body ?: JsonField.of(mutableListOf())).also { + checkKnown("body", it).add(body) } } fun jobId(jobId: String) = jobId(JsonField.of(jobId)) + /** + * Sets [Builder.jobId] to an arbitrary JSON value. + * + * You should usually call [Builder.jobId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun jobId(jobId: JsonField) = apply { this.jobId = jobId } fun status(status: Status) = status(JsonField.of(status)) + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [Status] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun status(status: JsonField) = apply { this.status = status } fun additionalProperties(additionalProperties: Map) = apply { @@ -139,15 +187,61 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [ManualAsyncJob]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .body() + * .jobId() + * .status() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): ManualAsyncJob = ManualAsyncJob( checkRequired("body", body).map { it.toImmutable() }, checkRequired("jobId", jobId), checkRequired("status", status), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): ManualAsyncJob = apply { + if (validated) { + return@apply + } + + body() + jobId() + status().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (body.asKnown().getOrNull()?.size ?: 0) + + (if (jobId.asKnown().isPresent) 1 else 0) + + (status.asKnown().getOrNull()?.validity() ?: 0) + class Status @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -244,6 +338,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Status = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Money.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Money.kt index 547abdfa..c9badec1 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Money.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Money.kt @@ -10,53 +10,68 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class Money -@JsonCreator private constructor( - @JsonProperty("amount") @ExcludeMissing private val amount: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val amount: JsonField, + private val currency: JsonField, + private val additionalProperties: MutableMap, ) { - /** Amount for money object (in cents) */ - fun amount(): Optional = Optional.ofNullable(amount.getNullable("amount")) - - fun currency(): Optional = Optional.ofNullable(currency.getNullable("currency")) - - /** Amount for money object (in cents) */ + @JsonCreator + private constructor( + @JsonProperty("amount") @ExcludeMissing amount: JsonField = JsonMissing.of(), + @JsonProperty("currency") @ExcludeMissing currency: JsonField = JsonMissing.of(), + ) : this(amount, currency, mutableMapOf()) + + /** + * Amount for money object (in cents) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") + + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Money = apply { - if (validated) { - return@apply - } - - amount() - currency() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Money]. */ @JvmStatic fun builder() = Builder() } @@ -77,18 +92,32 @@ private constructor( /** Amount for money object (in cents) */ fun amount(amount: Long?) = amount(JsonField.ofNullable(amount)) - /** Amount for money object (in cents) */ + /** + * Alias for [Builder.amount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun amount(amount: Long) = amount(amount as Long?) - /** Amount for money object (in cents) */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun amount(amount: Optional) = amount(amount.orElse(null) as Long?) + /** Alias for calling [Builder.amount] with `amount.orElse(null)`. */ + fun amount(amount: Optional) = amount(amount.getOrNull()) - /** Amount for money object (in cents) */ + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun currency(currency: String) = currency(JsonField.of(currency)) + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } fun additionalProperties(additionalProperties: Map) = apply { @@ -110,9 +139,43 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Money = Money(amount, currency, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Money]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Money = Money(amount, currency, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Money = apply { + if (validated) { + return@apply + } + + amount() + currency() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + (if (currency.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/OperationSupport.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/OperationSupport.kt index 2cd1bc73..170e62fd 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/OperationSupport.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/OperationSupport.kt @@ -114,6 +114,32 @@ class OperationSupport @JsonCreator private constructor(private val value: JsonF fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): OperationSupport = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/OperationSupportMatrix.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/OperationSupportMatrix.kt index 56ac7c5f..67fbb130 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/OperationSupportMatrix.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/OperationSupportMatrix.kt @@ -10,31 +10,35 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class OperationSupportMatrix -@JsonCreator private constructor( - @JsonProperty("create") - @ExcludeMissing - private val create: JsonField = JsonMissing.of(), - @JsonProperty("delete") - @ExcludeMissing - private val delete: JsonField = JsonMissing.of(), - @JsonProperty("read") - @ExcludeMissing - private val read: JsonField = JsonMissing.of(), - @JsonProperty("update") - @ExcludeMissing - private val update: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val create: JsonField, + private val delete: JsonField, + private val read: JsonField, + private val update: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("create") + @ExcludeMissing + create: JsonField = JsonMissing.of(), + @JsonProperty("delete") + @ExcludeMissing + delete: JsonField = JsonMissing.of(), + @JsonProperty("read") @ExcludeMissing read: JsonField = JsonMissing.of(), + @JsonProperty("update") + @ExcludeMissing + update: JsonField = JsonMissing.of(), + ) : this(create, delete, read, update, mutableMapOf()) + /** * - `supported`: This operation is supported by both the provider and Finch * - `not_supported_by_finch`: This operation is not supported by Finch but supported by the @@ -43,8 +47,11 @@ private constructor( * cannot support * - `client_access_only`: This behavior is supported by the provider, but only available to the * client and not to Finch + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun create(): Optional = Optional.ofNullable(create.getNullable("create")) + fun create(): Optional = create.getOptional("create") /** * - `supported`: This operation is supported by both the provider and Finch @@ -54,8 +61,11 @@ private constructor( * cannot support * - `client_access_only`: This behavior is supported by the provider, but only available to the * client and not to Finch + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun delete(): Optional = Optional.ofNullable(delete.getNullable("delete")) + fun delete(): Optional = delete.getOptional("delete") /** * - `supported`: This operation is supported by both the provider and Finch @@ -65,8 +75,11 @@ private constructor( * cannot support * - `client_access_only`: This behavior is supported by the provider, but only available to the * client and not to Finch + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun read(): Optional = Optional.ofNullable(read.getNullable("read")) + fun read(): Optional = read.getOptional("read") /** * - `supported`: This operation is supported by both the provider and Finch @@ -76,75 +89,55 @@ private constructor( * cannot support * - `client_access_only`: This behavior is supported by the provider, but only available to the * client and not to Finch + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun update(): Optional = Optional.ofNullable(update.getNullable("update")) + fun update(): Optional = update.getOptional("update") /** - * - `supported`: This operation is supported by both the provider and Finch - * - `not_supported_by_finch`: This operation is not supported by Finch but supported by the - * provider - * - `not_supported_by_provider`: This operation is not supported by the provider, so Finch - * cannot support - * - `client_access_only`: This behavior is supported by the provider, but only available to the - * client and not to Finch + * Returns the raw JSON value of [create]. + * + * Unlike [create], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("create") @ExcludeMissing fun _create(): JsonField = create /** - * - `supported`: This operation is supported by both the provider and Finch - * - `not_supported_by_finch`: This operation is not supported by Finch but supported by the - * provider - * - `not_supported_by_provider`: This operation is not supported by the provider, so Finch - * cannot support - * - `client_access_only`: This behavior is supported by the provider, but only available to the - * client and not to Finch + * Returns the raw JSON value of [delete]. + * + * Unlike [delete], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("delete") @ExcludeMissing fun _delete(): JsonField = delete /** - * - `supported`: This operation is supported by both the provider and Finch - * - `not_supported_by_finch`: This operation is not supported by Finch but supported by the - * provider - * - `not_supported_by_provider`: This operation is not supported by the provider, so Finch - * cannot support - * - `client_access_only`: This behavior is supported by the provider, but only available to the - * client and not to Finch + * Returns the raw JSON value of [read]. + * + * Unlike [read], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("read") @ExcludeMissing fun _read(): JsonField = read /** - * - `supported`: This operation is supported by both the provider and Finch - * - `not_supported_by_finch`: This operation is not supported by Finch but supported by the - * provider - * - `not_supported_by_provider`: This operation is not supported by the provider, so Finch - * cannot support - * - `client_access_only`: This behavior is supported by the provider, but only available to the - * client and not to Finch + * Returns the raw JSON value of [update]. + * + * Unlike [update], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("update") @ExcludeMissing fun _update(): JsonField = update + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): OperationSupportMatrix = apply { - if (validated) { - return@apply - } - - create() - delete() - read() - update() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [OperationSupportMatrix]. */ @JvmStatic fun builder() = Builder() } @@ -178,13 +171,11 @@ private constructor( fun create(create: OperationSupport) = create(JsonField.of(create)) /** - * - `supported`: This operation is supported by both the provider and Finch - * - `not_supported_by_finch`: This operation is not supported by Finch but supported by the - * provider - * - `not_supported_by_provider`: This operation is not supported by the provider, so Finch - * cannot support - * - `client_access_only`: This behavior is supported by the provider, but only available to - * the client and not to Finch + * Sets [Builder.create] to an arbitrary JSON value. + * + * You should usually call [Builder.create] with a well-typed [OperationSupport] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun create(create: JsonField) = apply { this.create = create } @@ -200,13 +191,11 @@ private constructor( fun delete(delete: OperationSupport) = delete(JsonField.of(delete)) /** - * - `supported`: This operation is supported by both the provider and Finch - * - `not_supported_by_finch`: This operation is not supported by Finch but supported by the - * provider - * - `not_supported_by_provider`: This operation is not supported by the provider, so Finch - * cannot support - * - `client_access_only`: This behavior is supported by the provider, but only available to - * the client and not to Finch + * Sets [Builder.delete] to an arbitrary JSON value. + * + * You should usually call [Builder.delete] with a well-typed [OperationSupport] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun delete(delete: JsonField) = apply { this.delete = delete } @@ -222,13 +211,11 @@ private constructor( fun read(read: OperationSupport) = read(JsonField.of(read)) /** - * - `supported`: This operation is supported by both the provider and Finch - * - `not_supported_by_finch`: This operation is not supported by Finch but supported by the - * provider - * - `not_supported_by_provider`: This operation is not supported by the provider, so Finch - * cannot support - * - `client_access_only`: This behavior is supported by the provider, but only available to - * the client and not to Finch + * Sets [Builder.read] to an arbitrary JSON value. + * + * You should usually call [Builder.read] with a well-typed [OperationSupport] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun read(read: JsonField) = apply { this.read = read } @@ -244,13 +231,11 @@ private constructor( fun update(update: OperationSupport) = update(JsonField.of(update)) /** - * - `supported`: This operation is supported by both the provider and Finch - * - `not_supported_by_finch`: This operation is not supported by Finch but supported by the - * provider - * - `not_supported_by_provider`: This operation is not supported by the provider, so Finch - * cannot support - * - `client_access_only`: This behavior is supported by the provider, but only available to - * the client and not to Finch + * Sets [Builder.update] to an arbitrary JSON value. + * + * You should usually call [Builder.update] with a well-typed [OperationSupport] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun update(update: JsonField) = apply { this.update = update } @@ -273,10 +258,55 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [OperationSupportMatrix]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): OperationSupportMatrix = - OperationSupportMatrix(create, delete, read, update, additionalProperties.toImmutable()) + OperationSupportMatrix( + create, + delete, + read, + update, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): OperationSupportMatrix = apply { + if (validated) { + return@apply + } + + create().ifPresent { it.validate() } + delete().ifPresent { it.validate() } + read().ifPresent { it.validate() } + update().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (create.asKnown().getOrNull()?.validity() ?: 0) + + (delete.asKnown().getOrNull()?.validity() ?: 0) + + (read.asKnown().getOrNull()?.validity() ?: 0) + + (update.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Paging.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Paging.kt index d75f67c8..c7cc6fb4 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Paging.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Paging.kt @@ -10,53 +10,69 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional -@NoAutoDetect class Paging -@JsonCreator private constructor( - @JsonProperty("count") @ExcludeMissing private val count: JsonField = JsonMissing.of(), - @JsonProperty("offset") @ExcludeMissing private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val count: JsonField, + private val offset: JsonField, + private val additionalProperties: MutableMap, ) { - /** The total number of elements for the entire query (not just the given page) */ - fun count(): Optional = Optional.ofNullable(count.getNullable("count")) - - /** The current start index of the returned list of elements */ - fun offset(): Optional = Optional.ofNullable(offset.getNullable("offset")) - - /** The total number of elements for the entire query (not just the given page) */ + @JsonCreator + private constructor( + @JsonProperty("count") @ExcludeMissing count: JsonField = JsonMissing.of(), + @JsonProperty("offset") @ExcludeMissing offset: JsonField = JsonMissing.of(), + ) : this(count, offset, mutableMapOf()) + + /** + * The total number of elements for the entire query (not just the given page) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun count(): Optional = count.getOptional("count") + + /** + * The current start index of the returned list of elements + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun offset(): Optional = offset.getOptional("offset") + + /** + * Returns the raw JSON value of [count]. + * + * Unlike [count], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("count") @ExcludeMissing fun _count(): JsonField = count - /** The current start index of the returned list of elements */ + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Paging = apply { - if (validated) { - return@apply - } - - count() - offset() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Paging]. */ @JvmStatic fun builder() = Builder() } @@ -77,13 +93,23 @@ private constructor( /** The total number of elements for the entire query (not just the given page) */ fun count(count: Long) = count(JsonField.of(count)) - /** The total number of elements for the entire query (not just the given page) */ + /** + * Sets [Builder.count] to an arbitrary JSON value. + * + * You should usually call [Builder.count] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun count(count: JsonField) = apply { this.count = count } /** The current start index of the returned list of elements */ fun offset(offset: Long) = offset(JsonField.of(offset)) - /** The current start index of the returned list of elements */ + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun offset(offset: JsonField) = apply { this.offset = offset } fun additionalProperties(additionalProperties: Map) = apply { @@ -105,9 +131,43 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Paging = Paging(count, offset, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Paging]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Paging = Paging(count, offset, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Paging = apply { + if (validated) { + return@apply + } + + count() + offset() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (count.asKnown().isPresent) 1 else 0) + (if (offset.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayGroupListResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayGroupListResponse.kt index 55d23e26..608a9101 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayGroupListResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayGroupListResponse.kt @@ -11,67 +11,94 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class PayGroupListResponse -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("pay_frequencies") - @ExcludeMissing - private val payFrequencies: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val name: JsonField, + private val payFrequencies: JsonField>, + private val additionalProperties: MutableMap, ) { - /** Finch id (uuidv4) for the pay group */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - /** Name of the pay group */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** List of pay frequencies associated with this pay group */ + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("pay_frequencies") + @ExcludeMissing + payFrequencies: JsonField> = JsonMissing.of(), + ) : this(id, name, payFrequencies, mutableMapOf()) + + /** + * Finch id (uuidv4) for the pay group + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Name of the pay group + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * List of pay frequencies associated with this pay group + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun payFrequencies(): Optional> = - Optional.ofNullable(payFrequencies.getNullable("pay_frequencies")) + payFrequencies.getOptional("pay_frequencies") - /** Finch id (uuidv4) for the pay group */ + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - /** Name of the pay group */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** List of pay frequencies associated with this pay group */ + /** + * Returns the raw JSON value of [payFrequencies]. + * + * Unlike [payFrequencies], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("pay_frequencies") @ExcludeMissing fun _payFrequencies(): JsonField> = payFrequencies + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PayGroupListResponse = apply { - if (validated) { - return@apply - } - - id() - name() - payFrequencies() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [PayGroupListResponse]. */ @JvmStatic fun builder() = Builder() } @@ -94,35 +121,49 @@ private constructor( /** Finch id (uuidv4) for the pay group */ fun id(id: String) = id(JsonField.of(id)) - /** Finch id (uuidv4) for the pay group */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } /** Name of the pay group */ fun name(name: String) = name(JsonField.of(name)) - /** Name of the pay group */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } /** List of pay frequencies associated with this pay group */ fun payFrequencies(payFrequencies: List) = payFrequencies(JsonField.of(payFrequencies)) - /** List of pay frequencies associated with this pay group */ + /** + * Sets [Builder.payFrequencies] to an arbitrary JSON value. + * + * You should usually call [Builder.payFrequencies] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun payFrequencies(payFrequencies: JsonField>) = apply { this.payFrequencies = payFrequencies.map { it.toMutableList() } } - /** List of pay frequencies associated with this pay group */ + /** + * Adds a single [PayFrequency] to [payFrequencies]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addPayFrequency(payFrequency: PayFrequency) = apply { payFrequencies = - (payFrequencies ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(payFrequency) + (payFrequencies ?: JsonField.of(mutableListOf())).also { + checkKnown("payFrequencies", it).add(payFrequency) } } @@ -145,15 +186,52 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PayGroupListResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): PayGroupListResponse = PayGroupListResponse( id, name, (payFrequencies ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): PayGroupListResponse = apply { + if (validated) { + return@apply + } + + id() + name() + payFrequencies().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (payFrequencies.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + class PayFrequency @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -283,6 +361,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): PayFrequency = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayGroupRetrieveResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayGroupRetrieveResponse.kt index 40f1c2b2..e6e2c27b 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayGroupRetrieveResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayGroupRetrieveResponse.kt @@ -11,76 +11,122 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class PayGroupRetrieveResponse -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("individual_ids") - @ExcludeMissing - private val individualIds: JsonField> = JsonMissing.of(), - @JsonProperty("name") @ExcludeMissing private val name: JsonField = JsonMissing.of(), - @JsonProperty("pay_frequencies") - @ExcludeMissing - private val payFrequencies: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val individualIds: JsonField>, + private val name: JsonField, + private val payFrequencies: JsonField>, + private val additionalProperties: MutableMap, ) { - /** Finch id (uuidv4) for the pay group */ + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("individual_ids") + @ExcludeMissing + individualIds: JsonField> = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("pay_frequencies") + @ExcludeMissing + payFrequencies: JsonField> = JsonMissing.of(), + ) : this(id, individualIds, name, payFrequencies, mutableMapOf()) + + /** + * Finch id (uuidv4) for the pay group + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun id(): String = id.getRequired("id") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun individualIds(): List = individualIds.getRequired("individual_ids") - /** Name of the pay group */ + /** + * Name of the pay group + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun name(): String = name.getRequired("name") - /** List of pay frequencies associated with this pay group */ + /** + * List of pay frequencies associated with this pay group + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun payFrequencies(): List = payFrequencies.getRequired("pay_frequencies") - /** Finch id (uuidv4) for the pay group */ + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [individualIds]. + * + * Unlike [individualIds], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("individual_ids") @ExcludeMissing fun _individualIds(): JsonField> = individualIds - /** Name of the pay group */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** List of pay frequencies associated with this pay group */ + /** + * Returns the raw JSON value of [payFrequencies]. + * + * Unlike [payFrequencies], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("pay_frequencies") @ExcludeMissing fun _payFrequencies(): JsonField> = payFrequencies + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PayGroupRetrieveResponse = apply { - if (validated) { - return@apply - } - - id() - individualIds() - name() - payFrequencies() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [PayGroupRetrieveResponse]. + * + * The following fields are required: + * ```java + * .id() + * .individualIds() + * .name() + * .payFrequencies() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -105,54 +151,74 @@ private constructor( /** Finch id (uuidv4) for the pay group */ fun id(id: String) = id(JsonField.of(id)) - /** Finch id (uuidv4) for the pay group */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun individualIds(individualIds: List) = individualIds(JsonField.of(individualIds)) + /** + * Sets [Builder.individualIds] to an arbitrary JSON value. + * + * You should usually call [Builder.individualIds] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun individualIds(individualIds: JsonField>) = apply { this.individualIds = individualIds.map { it.toMutableList() } } + /** + * Adds a single [String] to [individualIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addIndividualId(individualId: String) = apply { individualIds = - (individualIds ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(individualId) + (individualIds ?: JsonField.of(mutableListOf())).also { + checkKnown("individualIds", it).add(individualId) } } /** Name of the pay group */ fun name(name: String) = name(JsonField.of(name)) - /** Name of the pay group */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } /** List of pay frequencies associated with this pay group */ fun payFrequencies(payFrequencies: List) = payFrequencies(JsonField.of(payFrequencies)) - /** List of pay frequencies associated with this pay group */ + /** + * Sets [Builder.payFrequencies] to an arbitrary JSON value. + * + * You should usually call [Builder.payFrequencies] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun payFrequencies(payFrequencies: JsonField>) = apply { this.payFrequencies = payFrequencies.map { it.toMutableList() } } - /** List of pay frequencies associated with this pay group */ + /** + * Adds a single [PayFrequency] to [payFrequencies]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addPayFrequency(payFrequency: PayFrequency) = apply { payFrequencies = - (payFrequencies ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(payFrequency) + (payFrequencies ?: JsonField.of(mutableListOf())).also { + checkKnown("payFrequencies", it).add(payFrequency) } } @@ -175,16 +241,65 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PayGroupRetrieveResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .individualIds() + * .name() + * .payFrequencies() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): PayGroupRetrieveResponse = PayGroupRetrieveResponse( checkRequired("id", id), checkRequired("individualIds", individualIds).map { it.toImmutable() }, checkRequired("name", name), checkRequired("payFrequencies", payFrequencies).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): PayGroupRetrieveResponse = apply { + if (validated) { + return@apply + } + + id() + individualIds() + name() + payFrequencies().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (individualIds.asKnown().getOrNull()?.size ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (payFrequencies.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + class PayFrequency @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -314,6 +429,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): PayFrequency = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatement.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatement.kt index 0553227d..ae0b753f 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatement.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatement.kt @@ -11,142 +11,238 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class PayStatement -@JsonCreator private constructor( - @JsonProperty("earnings") - @ExcludeMissing - private val earnings: JsonField> = JsonMissing.of(), - @JsonProperty("employee_deductions") - @ExcludeMissing - private val employeeDeductions: JsonField> = JsonMissing.of(), - @JsonProperty("employer_contributions") - @ExcludeMissing - private val employerContributions: JsonField> = JsonMissing.of(), - @JsonProperty("gross_pay") - @ExcludeMissing - private val grossPay: JsonField = JsonMissing.of(), - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonProperty("net_pay") - @ExcludeMissing - private val netPay: JsonField = JsonMissing.of(), - @JsonProperty("payment_method") - @ExcludeMissing - private val paymentMethod: JsonField = JsonMissing.of(), - @JsonProperty("taxes") - @ExcludeMissing - private val taxes: JsonField> = JsonMissing.of(), - @JsonProperty("total_hours") - @ExcludeMissing - private val totalHours: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val earnings: JsonField>, + private val employeeDeductions: JsonField>, + private val employerContributions: JsonField>, + private val grossPay: JsonField, + private val individualId: JsonField, + private val netPay: JsonField, + private val paymentMethod: JsonField, + private val taxes: JsonField>, + private val totalHours: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The array of earnings objects associated with this pay statement */ - fun earnings(): Optional> = Optional.ofNullable(earnings.getNullable("earnings")) - - /** The array of deductions objects associated with this pay statement. */ + @JsonCreator + private constructor( + @JsonProperty("earnings") + @ExcludeMissing + earnings: JsonField> = JsonMissing.of(), + @JsonProperty("employee_deductions") + @ExcludeMissing + employeeDeductions: JsonField> = JsonMissing.of(), + @JsonProperty("employer_contributions") + @ExcludeMissing + employerContributions: JsonField> = JsonMissing.of(), + @JsonProperty("gross_pay") @ExcludeMissing grossPay: JsonField = JsonMissing.of(), + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of(), + @JsonProperty("net_pay") @ExcludeMissing netPay: JsonField = JsonMissing.of(), + @JsonProperty("payment_method") + @ExcludeMissing + paymentMethod: JsonField = JsonMissing.of(), + @JsonProperty("taxes") @ExcludeMissing taxes: JsonField> = JsonMissing.of(), + @JsonProperty("total_hours") + @ExcludeMissing + totalHours: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this( + earnings, + employeeDeductions, + employerContributions, + grossPay, + individualId, + netPay, + paymentMethod, + taxes, + totalHours, + type, + mutableMapOf(), + ) + + /** + * The array of earnings objects associated with this pay statement + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun earnings(): Optional> = earnings.getOptional("earnings") + + /** + * The array of deductions objects associated with this pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun employeeDeductions(): Optional> = - Optional.ofNullable(employeeDeductions.getNullable("employee_deductions")) + employeeDeductions.getOptional("employee_deductions") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun employerContributions(): Optional> = - Optional.ofNullable(employerContributions.getNullable("employer_contributions")) - - fun grossPay(): Optional = Optional.ofNullable(grossPay.getNullable("gross_pay")) - - /** A stable Finch `id` (UUID v4) for an individual in the company */ - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) - - fun netPay(): Optional = Optional.ofNullable(netPay.getNullable("net_pay")) - - /** The payment method. */ - fun paymentMethod(): Optional = - Optional.ofNullable(paymentMethod.getNullable("payment_method")) - - /** The array of taxes objects associated with this pay statement. */ - fun taxes(): Optional> = Optional.ofNullable(taxes.getNullable("taxes")) - - /** The number of hours worked for this pay period */ - fun totalHours(): Optional = Optional.ofNullable(totalHours.getNullable("total_hours")) - - /** The type of the payment associated with the pay statement. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** The array of earnings objects associated with this pay statement */ + employerContributions.getOptional("employer_contributions") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun grossPay(): Optional = grossPay.getOptional("gross_pay") + + /** + * A stable Finch `id` (UUID v4) for an individual in the company + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun netPay(): Optional = netPay.getOptional("net_pay") + + /** + * The payment method. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun paymentMethod(): Optional = paymentMethod.getOptional("payment_method") + + /** + * The array of taxes objects associated with this pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun taxes(): Optional> = taxes.getOptional("taxes") + + /** + * The number of hours worked for this pay period + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun totalHours(): Optional = totalHours.getOptional("total_hours") + + /** + * The type of the payment associated with the pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [earnings]. + * + * Unlike [earnings], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("earnings") @ExcludeMissing fun _earnings(): JsonField> = earnings - /** The array of deductions objects associated with this pay statement. */ + /** + * Returns the raw JSON value of [employeeDeductions]. + * + * Unlike [employeeDeductions], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("employee_deductions") @ExcludeMissing fun _employeeDeductions(): JsonField> = employeeDeductions + /** + * Returns the raw JSON value of [employerContributions]. + * + * Unlike [employerContributions], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("employer_contributions") @ExcludeMissing fun _employerContributions(): JsonField> = employerContributions + /** + * Returns the raw JSON value of [grossPay]. + * + * Unlike [grossPay], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("gross_pay") @ExcludeMissing fun _grossPay(): JsonField = grossPay - /** A stable Finch `id` (UUID v4) for an individual in the company */ + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + /** + * Returns the raw JSON value of [netPay]. + * + * Unlike [netPay], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("net_pay") @ExcludeMissing fun _netPay(): JsonField = netPay - /** The payment method. */ + /** + * Returns the raw JSON value of [paymentMethod]. + * + * Unlike [paymentMethod], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("payment_method") @ExcludeMissing fun _paymentMethod(): JsonField = paymentMethod - /** The array of taxes objects associated with this pay statement. */ + /** + * Returns the raw JSON value of [taxes]. + * + * Unlike [taxes], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("taxes") @ExcludeMissing fun _taxes(): JsonField> = taxes - /** The number of hours worked for this pay period */ + /** + * Returns the raw JSON value of [totalHours]. + * + * Unlike [totalHours], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("total_hours") @ExcludeMissing fun _totalHours(): JsonField = totalHours - /** The type of the payment associated with the pay statement. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PayStatement = apply { - if (validated) { - return@apply - } - - earnings().ifPresent { it.forEach { it?.validate() } } - employeeDeductions().ifPresent { it.forEach { it?.validate() } } - employerContributions().ifPresent { it.forEach { it?.validate() } } - grossPay().ifPresent { it.validate() } - individualId() - netPay().ifPresent { it.validate() } - paymentMethod() - taxes().ifPresent { it.forEach { it?.validate() } } - totalHours() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [PayStatement]. */ @JvmStatic fun builder() = Builder() } @@ -183,25 +279,29 @@ private constructor( /** The array of earnings objects associated with this pay statement */ fun earnings(earnings: List?) = earnings(JsonField.ofNullable(earnings)) - /** The array of earnings objects associated with this pay statement */ - fun earnings(earnings: Optional>) = earnings(earnings.orElse(null)) + /** Alias for calling [Builder.earnings] with `earnings.orElse(null)`. */ + fun earnings(earnings: Optional>) = earnings(earnings.getOrNull()) - /** The array of earnings objects associated with this pay statement */ + /** + * Sets [Builder.earnings] to an arbitrary JSON value. + * + * You should usually call [Builder.earnings] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun earnings(earnings: JsonField>) = apply { this.earnings = earnings.map { it.toMutableList() } } - /** The array of earnings objects associated with this pay statement */ + /** + * Adds a single [Earning] to [earnings]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addEarning(earning: Earning) = apply { earnings = - (earnings ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(earning) + (earnings ?: JsonField.of(mutableListOf())).also { + checkKnown("earnings", it).add(earning) } } @@ -209,82 +309,124 @@ private constructor( fun employeeDeductions(employeeDeductions: List?) = employeeDeductions(JsonField.ofNullable(employeeDeductions)) - /** The array of deductions objects associated with this pay statement. */ + /** + * Alias for calling [Builder.employeeDeductions] with `employeeDeductions.orElse(null)`. + */ fun employeeDeductions(employeeDeductions: Optional>) = - employeeDeductions(employeeDeductions.orElse(null)) + employeeDeductions(employeeDeductions.getOrNull()) - /** The array of deductions objects associated with this pay statement. */ + /** + * Sets [Builder.employeeDeductions] to an arbitrary JSON value. + * + * You should usually call [Builder.employeeDeductions] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun employeeDeductions(employeeDeductions: JsonField>) = apply { this.employeeDeductions = employeeDeductions.map { it.toMutableList() } } - /** The array of deductions objects associated with this pay statement. */ + /** + * Adds a single [EmployeeDeduction] to [employeeDeductions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addEmployeeDeduction(employeeDeduction: EmployeeDeduction) = apply { employeeDeductions = - (employeeDeductions ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(employeeDeduction) + (employeeDeductions ?: JsonField.of(mutableListOf())).also { + checkKnown("employeeDeductions", it).add(employeeDeduction) } } fun employerContributions(employerContributions: List?) = employerContributions(JsonField.ofNullable(employerContributions)) + /** + * Alias for calling [Builder.employerContributions] with + * `employerContributions.orElse(null)`. + */ fun employerContributions(employerContributions: Optional>) = - employerContributions(employerContributions.orElse(null)) + employerContributions(employerContributions.getOrNull()) + /** + * Sets [Builder.employerContributions] to an arbitrary JSON value. + * + * You should usually call [Builder.employerContributions] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun employerContributions(employerContributions: JsonField>) = apply { this.employerContributions = employerContributions.map { it.toMutableList() } } + /** + * Adds a single [EmployerContribution] to [employerContributions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addEmployerContribution(employerContribution: EmployerContribution) = apply { employerContributions = - (employerContributions ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(employerContribution) + (employerContributions ?: JsonField.of(mutableListOf())).also { + checkKnown("employerContributions", it).add(employerContribution) } } fun grossPay(grossPay: Money?) = grossPay(JsonField.ofNullable(grossPay)) - fun grossPay(grossPay: Optional) = grossPay(grossPay.orElse(null)) + /** Alias for calling [Builder.grossPay] with `grossPay.orElse(null)`. */ + fun grossPay(grossPay: Optional) = grossPay(grossPay.getOrNull()) + /** + * Sets [Builder.grossPay] to an arbitrary JSON value. + * + * You should usually call [Builder.grossPay] with a well-typed [Money] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun grossPay(grossPay: JsonField) = apply { this.grossPay = grossPay } /** A stable Finch `id` (UUID v4) for an individual in the company */ fun individualId(individualId: String) = individualId(JsonField.of(individualId)) - /** A stable Finch `id` (UUID v4) for an individual in the company */ + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } fun netPay(netPay: Money?) = netPay(JsonField.ofNullable(netPay)) - fun netPay(netPay: Optional) = netPay(netPay.orElse(null)) + /** Alias for calling [Builder.netPay] with `netPay.orElse(null)`. */ + fun netPay(netPay: Optional) = netPay(netPay.getOrNull()) + /** + * Sets [Builder.netPay] to an arbitrary JSON value. + * + * You should usually call [Builder.netPay] with a well-typed [Money] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun netPay(netPay: JsonField) = apply { this.netPay = netPay } /** The payment method. */ fun paymentMethod(paymentMethod: PaymentMethod?) = paymentMethod(JsonField.ofNullable(paymentMethod)) - /** The payment method. */ + /** Alias for calling [Builder.paymentMethod] with `paymentMethod.orElse(null)`. */ fun paymentMethod(paymentMethod: Optional) = - paymentMethod(paymentMethod.orElse(null)) + paymentMethod(paymentMethod.getOrNull()) - /** The payment method. */ + /** + * Sets [Builder.paymentMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.paymentMethod] with a well-typed [PaymentMethod] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun paymentMethod(paymentMethod: JsonField) = apply { this.paymentMethod = paymentMethod } @@ -292,49 +434,64 @@ private constructor( /** The array of taxes objects associated with this pay statement. */ fun taxes(taxes: List?) = taxes(JsonField.ofNullable(taxes)) - /** The array of taxes objects associated with this pay statement. */ - fun taxes(taxes: Optional>) = taxes(taxes.orElse(null)) + /** Alias for calling [Builder.taxes] with `taxes.orElse(null)`. */ + fun taxes(taxes: Optional>) = taxes(taxes.getOrNull()) - /** The array of taxes objects associated with this pay statement. */ + /** + * Sets [Builder.taxes] to an arbitrary JSON value. + * + * You should usually call [Builder.taxes] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun taxes(taxes: JsonField>) = apply { this.taxes = taxes.map { it.toMutableList() } } - /** The array of taxes objects associated with this pay statement. */ + /** + * Adds a single [Tax] to [taxes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addTax(tax: Tax) = apply { taxes = - (taxes ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(tax) - } + (taxes ?: JsonField.of(mutableListOf())).also { checkKnown("taxes", it).add(tax) } } /** The number of hours worked for this pay period */ fun totalHours(totalHours: Double?) = totalHours(JsonField.ofNullable(totalHours)) - /** The number of hours worked for this pay period */ + /** + * Alias for [Builder.totalHours]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun totalHours(totalHours: Double) = totalHours(totalHours as Double?) - /** The number of hours worked for this pay period */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun totalHours(totalHours: Optional) = - totalHours(totalHours.orElse(null) as Double?) + /** Alias for calling [Builder.totalHours] with `totalHours.orElse(null)`. */ + fun totalHours(totalHours: Optional) = totalHours(totalHours.getOrNull()) - /** The number of hours worked for this pay period */ + /** + * Sets [Builder.totalHours] to an arbitrary JSON value. + * + * You should usually call [Builder.totalHours] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun totalHours(totalHours: JsonField) = apply { this.totalHours = totalHours } /** The type of the payment associated with the pay statement. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** The type of the payment associated with the pay statement. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** The type of the payment associated with the pay statement. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -356,6 +513,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PayStatement]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): PayStatement = PayStatement( (earnings ?: JsonMissing.of()).map { it.toImmutable() }, @@ -368,101 +530,189 @@ private constructor( (taxes ?: JsonMissing.of()).map { it.toImmutable() }, totalHours, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): PayStatement = apply { + if (validated) { + return@apply + } + + earnings().ifPresent { it.forEach { it?.validate() } } + employeeDeductions().ifPresent { it.forEach { it?.validate() } } + employerContributions().ifPresent { it.forEach { it?.validate() } } + grossPay().ifPresent { it.validate() } + individualId() + netPay().ifPresent { it.validate() } + paymentMethod().ifPresent { it.validate() } + taxes().ifPresent { it.forEach { it?.validate() } } + totalHours() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (earnings.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (employeeDeductions.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } + ?: 0) + + (employerContributions.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } + ?: 0) + + (grossPay.asKnown().getOrNull()?.validity() ?: 0) + + (if (individualId.asKnown().isPresent) 1 else 0) + + (netPay.asKnown().getOrNull()?.validity() ?: 0) + + (paymentMethod.asKnown().getOrNull()?.validity() ?: 0) + + (taxes.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (totalHours.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Earning - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("attributes") - @ExcludeMissing - private val attributes: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("hours") - @ExcludeMissing - private val hours: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val amount: JsonField, + private val attributes: JsonField, + private val currency: JsonField, + private val hours: JsonField, + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The earnings amount in cents. */ - fun amount(): Optional = Optional.ofNullable(amount.getNullable("amount")) + @JsonCreator + private constructor( + @JsonProperty("amount") @ExcludeMissing amount: JsonField = JsonMissing.of(), + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("hours") @ExcludeMissing hours: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(amount, attributes, currency, hours, name, type, mutableMapOf()) + + /** + * The earnings amount in cents. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") - fun attributes(): Optional = - Optional.ofNullable(attributes.getNullable("attributes")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") - /** The earnings currency code. */ - fun currency(): Optional = Optional.ofNullable(currency.getNullable("currency")) + /** + * The earnings currency code. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") /** * The number of hours associated with this earning. (For salaried employees, this could be * hours per pay period, `0` or `null`, depending on the provider). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun hours(): Optional = Optional.ofNullable(hours.getNullable("hours")) + fun hours(): Optional = hours.getOptional("hours") - /** The exact name of the deduction from the pay statement. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + /** + * The exact name of the deduction from the pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** The type of earning. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The type of earning. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") - /** The earnings amount in cents. */ + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("attributes") @ExcludeMissing fun _attributes(): JsonField = attributes - /** The earnings currency code. */ + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency /** - * The number of hours associated with this earning. (For salaried employees, this could be - * hours per pay period, `0` or `null`, depending on the provider). + * Returns the raw JSON value of [hours]. + * + * Unlike [hours], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("hours") @ExcludeMissing fun _hours(): JsonField = hours - /** The exact name of the deduction from the pay statement. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** The type of earning. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Earning = apply { - if (validated) { - return@apply - } - - amount() - attributes().ifPresent { it.validate() } - currency() - hours() - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Earning]. */ @JvmStatic fun builder() = Builder() } @@ -491,20 +741,37 @@ private constructor( /** The earnings amount in cents. */ fun amount(amount: Long?) = amount(JsonField.ofNullable(amount)) - /** The earnings amount in cents. */ + /** + * Alias for [Builder.amount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun amount(amount: Long) = amount(amount as Long?) - /** The earnings amount in cents. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun amount(amount: Optional) = amount(amount.orElse(null) as Long?) + /** Alias for calling [Builder.amount] with `amount.orElse(null)`. */ + fun amount(amount: Optional) = amount(amount.getOrNull()) - /** The earnings amount in cents. */ + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun attributes(attributes: Attributes?) = attributes(JsonField.ofNullable(attributes)) - fun attributes(attributes: Optional) = attributes(attributes.orElse(null)) + /** Alias for calling [Builder.attributes] with `attributes.orElse(null)`. */ + fun attributes(attributes: Optional) = attributes(attributes.getOrNull()) + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun attributes(attributes: JsonField) = apply { this.attributes = attributes } @@ -512,10 +779,16 @@ private constructor( /** The earnings currency code. */ fun currency(currency: String?) = currency(JsonField.ofNullable(currency)) - /** The earnings currency code. */ - fun currency(currency: Optional) = currency(currency.orElse(null)) + /** Alias for calling [Builder.currency] with `currency.orElse(null)`. */ + fun currency(currency: Optional) = currency(currency.getOrNull()) - /** The earnings currency code. */ + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } /** @@ -525,40 +798,52 @@ private constructor( fun hours(hours: Double?) = hours(JsonField.ofNullable(hours)) /** - * The number of hours associated with this earning. (For salaried employees, this could - * be hours per pay period, `0` or `null`, depending on the provider). + * Alias for [Builder.hours]. + * + * This unboxed primitive overload exists for backwards compatibility. */ fun hours(hours: Double) = hours(hours as Double?) - /** - * The number of hours associated with this earning. (For salaried employees, this could - * be hours per pay period, `0` or `null`, depending on the provider). - */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun hours(hours: Optional) = hours(hours.orElse(null) as Double?) + /** Alias for calling [Builder.hours] with `hours.orElse(null)`. */ + fun hours(hours: Optional) = hours(hours.getOrNull()) /** - * The number of hours associated with this earning. (For salaried employees, this could - * be hours per pay period, `0` or `null`, depending on the provider). + * Sets [Builder.hours] to an arbitrary JSON value. + * + * You should usually call [Builder.hours] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun hours(hours: JsonField) = apply { this.hours = hours } /** The exact name of the deduction from the pay statement. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The exact name of the deduction from the pay statement. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The exact name of the deduction from the pay statement. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } /** The type of earning. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** The type of earning. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** The type of earning. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -580,6 +865,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Earning]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Earning = Earning( amount, @@ -588,47 +878,93 @@ private constructor( hours, name, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Earning = apply { + if (validated) { + return@apply + } + + amount() + attributes().ifPresent { it.validate() } + currency() + hours() + name() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (hours.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Attributes - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Attributes = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Attributes]. */ @JvmStatic fun builder() = Builder() } @@ -646,6 +982,13 @@ private constructor( fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata } fun additionalProperties(additionalProperties: Map) = apply { @@ -670,56 +1013,90 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Attributes = Attributes(metadata, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Attributes = Attributes(metadata, additionalProperties.toMutableMap()) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + class Metadata - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + /** * The metadata to be attached to the entity by existing rules. It is a key-value * pairs where the values can be of any type (string, number, boolean, object, * array, etc.). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** - * The metadata to be attached to the entity by existing rules. It is a key-value - * pairs where the values can be of any type (string, number, boolean, object, - * array, etc.). + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Metadata]. */ @JvmStatic fun builder() = Builder() } @@ -743,9 +1120,11 @@ private constructor( fun metadata(metadata: InnerMetadata) = metadata(JsonField.of(metadata)) /** - * The metadata to be attached to the entity by existing rules. It is a - * key-value pairs where the values can be of any type (string, number, boolean, - * object, array, etc.). + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [InnerMetadata] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata @@ -773,40 +1152,66 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Metadata = Metadata(metadata, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(metadata, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + /** * The metadata to be attached to the entity by existing rules. It is a key-value * pairs where the values can be of any type (string, number, boolean, object, * array, etc.). */ - @NoAutoDetect class InnerMetadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): InnerMetadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [InnerMetadata]. + */ @JvmStatic fun builder() = Builder() } @@ -843,10 +1248,45 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [InnerMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): InnerMetadata = InnerMetadata(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): InnerMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1055,6 +1495,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1086,93 +1553,136 @@ private constructor( "Earning{amount=$amount, attributes=$attributes, currency=$currency, hours=$hours, name=$name, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class EmployeeDeduction - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("attributes") - @ExcludeMissing - private val attributes: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("pre_tax") - @ExcludeMissing - private val preTax: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val amount: JsonField, + private val attributes: JsonField, + private val currency: JsonField, + private val name: JsonField, + private val preTax: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The deduction amount in cents. */ - fun amount(): Optional = Optional.ofNullable(amount.getNullable("amount")) + @JsonCreator + private constructor( + @JsonProperty("amount") @ExcludeMissing amount: JsonField = JsonMissing.of(), + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("pre_tax") @ExcludeMissing preTax: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(amount, attributes, currency, name, preTax, type, mutableMapOf()) + + /** + * The deduction amount in cents. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") - fun attributes(): Optional = - Optional.ofNullable(attributes.getNullable("attributes")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") - /** The deduction currency. */ - fun currency(): Optional = Optional.ofNullable(currency.getNullable("currency")) + /** + * The deduction currency. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") - /** The deduction name from the pay statement. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + /** + * The deduction name from the pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** Boolean indicating if the deduction is pre-tax. */ - fun preTax(): Optional = Optional.ofNullable(preTax.getNullable("pre_tax")) + /** + * Boolean indicating if the deduction is pre-tax. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun preTax(): Optional = preTax.getOptional("pre_tax") - /** Type of benefit. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * Type of benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") - /** The deduction amount in cents. */ + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("attributes") @ExcludeMissing fun _attributes(): JsonField = attributes - /** The deduction currency. */ + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency - /** The deduction name from the pay statement. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** Boolean indicating if the deduction is pre-tax. */ + /** + * Returns the raw JSON value of [preTax]. + * + * Unlike [preTax], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("pre_tax") @ExcludeMissing fun _preTax(): JsonField = preTax - /** Type of benefit. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): EmployeeDeduction = apply { - if (validated) { - return@apply - } - - amount() - attributes().ifPresent { it.validate() } - currency() - name() - preTax() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [EmployeeDeduction]. */ @JvmStatic fun builder() = Builder() } @@ -1201,20 +1711,37 @@ private constructor( /** The deduction amount in cents. */ fun amount(amount: Long?) = amount(JsonField.ofNullable(amount)) - /** The deduction amount in cents. */ + /** + * Alias for [Builder.amount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun amount(amount: Long) = amount(amount as Long?) - /** The deduction amount in cents. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun amount(amount: Optional) = amount(amount.orElse(null) as Long?) + /** Alias for calling [Builder.amount] with `amount.orElse(null)`. */ + fun amount(amount: Optional) = amount(amount.getOrNull()) - /** The deduction amount in cents. */ + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun attributes(attributes: Attributes?) = attributes(JsonField.ofNullable(attributes)) - fun attributes(attributes: Optional) = attributes(attributes.orElse(null)) + /** Alias for calling [Builder.attributes] with `attributes.orElse(null)`. */ + fun attributes(attributes: Optional) = attributes(attributes.getOrNull()) + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun attributes(attributes: JsonField) = apply { this.attributes = attributes } @@ -1222,41 +1749,68 @@ private constructor( /** The deduction currency. */ fun currency(currency: String?) = currency(JsonField.ofNullable(currency)) - /** The deduction currency. */ - fun currency(currency: Optional) = currency(currency.orElse(null)) + /** Alias for calling [Builder.currency] with `currency.orElse(null)`. */ + fun currency(currency: Optional) = currency(currency.getOrNull()) - /** The deduction currency. */ + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } /** The deduction name from the pay statement. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The deduction name from the pay statement. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The deduction name from the pay statement. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } /** Boolean indicating if the deduction is pre-tax. */ fun preTax(preTax: Boolean?) = preTax(JsonField.ofNullable(preTax)) - /** Boolean indicating if the deduction is pre-tax. */ + /** + * Alias for [Builder.preTax]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun preTax(preTax: Boolean) = preTax(preTax as Boolean?) - /** Boolean indicating if the deduction is pre-tax. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun preTax(preTax: Optional) = preTax(preTax.orElse(null) as Boolean?) + /** Alias for calling [Builder.preTax] with `preTax.orElse(null)`. */ + fun preTax(preTax: Optional) = preTax(preTax.getOrNull()) - /** Boolean indicating if the deduction is pre-tax. */ + /** + * Sets [Builder.preTax] to an arbitrary JSON value. + * + * You should usually call [Builder.preTax] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun preTax(preTax: JsonField) = apply { this.preTax = preTax } /** Type of benefit. */ fun type(type: BenefitType?) = type(JsonField.ofNullable(type)) - /** Type of benefit. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** Type of benefit. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [BenefitType] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -1278,6 +1832,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [EmployeeDeduction]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): EmployeeDeduction = EmployeeDeduction( amount, @@ -1286,47 +1845,93 @@ private constructor( name, preTax, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): EmployeeDeduction = apply { + if (validated) { + return@apply + } + + amount() + attributes().ifPresent { it.validate() } + currency() + name() + preTax() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (preTax.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Attributes - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Attributes = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Attributes]. */ @JvmStatic fun builder() = Builder() } @@ -1344,6 +1949,13 @@ private constructor( fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata } fun additionalProperties(additionalProperties: Map) = apply { @@ -1368,56 +1980,90 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Attributes = Attributes(metadata, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Attributes = Attributes(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } - @NoAutoDetect + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + class Metadata - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + /** * The metadata to be attached to the entity by existing rules. It is a key-value * pairs where the values can be of any type (string, number, boolean, object, * array, etc.). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** - * The metadata to be attached to the entity by existing rules. It is a key-value - * pairs where the values can be of any type (string, number, boolean, object, - * array, etc.). + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Metadata]. */ @JvmStatic fun builder() = Builder() } @@ -1441,9 +2087,11 @@ private constructor( fun metadata(metadata: InnerMetadata) = metadata(JsonField.of(metadata)) /** - * The metadata to be attached to the entity by existing rules. It is a - * key-value pairs where the values can be of any type (string, number, boolean, - * object, array, etc.). + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [InnerMetadata] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata @@ -1471,40 +2119,66 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Metadata = Metadata(metadata, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + /** * The metadata to be attached to the entity by existing rules. It is a key-value * pairs where the values can be of any type (string, number, boolean, object, * array, etc.). */ - @NoAutoDetect class InnerMetadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): InnerMetadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [InnerMetadata]. + */ @JvmStatic fun builder() = Builder() } @@ -1541,10 +2215,45 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [InnerMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): InnerMetadata = InnerMetadata(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): InnerMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1617,83 +2326,119 @@ private constructor( "EmployeeDeduction{amount=$amount, attributes=$attributes, currency=$currency, name=$name, preTax=$preTax, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class EmployerContribution - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("attributes") - @ExcludeMissing - private val attributes: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val amount: JsonField, + private val attributes: JsonField, + private val currency: JsonField, + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The contribution amount in cents. */ - fun amount(): Optional = Optional.ofNullable(amount.getNullable("amount")) + @JsonCreator + private constructor( + @JsonProperty("amount") @ExcludeMissing amount: JsonField = JsonMissing.of(), + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(amount, attributes, currency, name, type, mutableMapOf()) + + /** + * The contribution amount in cents. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") - fun attributes(): Optional = - Optional.ofNullable(attributes.getNullable("attributes")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") - /** The contribution currency. */ - fun currency(): Optional = Optional.ofNullable(currency.getNullable("currency")) + /** + * The contribution currency. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") - /** The contribution name from the pay statement. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + /** + * The contribution name from the pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** Type of benefit. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * Type of benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") - /** The contribution amount in cents. */ + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("attributes") @ExcludeMissing fun _attributes(): JsonField = attributes - /** The contribution currency. */ + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency - /** The contribution name from the pay statement. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** Type of benefit. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): EmployerContribution = apply { - if (validated) { - return@apply - } - - amount() - attributes().ifPresent { it.validate() } - currency() - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [EmployerContribution]. */ @JvmStatic fun builder() = Builder() } @@ -1720,20 +2465,37 @@ private constructor( /** The contribution amount in cents. */ fun amount(amount: Long?) = amount(JsonField.ofNullable(amount)) - /** The contribution amount in cents. */ + /** + * Alias for [Builder.amount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun amount(amount: Long) = amount(amount as Long?) - /** The contribution amount in cents. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun amount(amount: Optional) = amount(amount.orElse(null) as Long?) + /** Alias for calling [Builder.amount] with `amount.orElse(null)`. */ + fun amount(amount: Optional) = amount(amount.getOrNull()) - /** The contribution amount in cents. */ + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun attributes(attributes: Attributes?) = attributes(JsonField.ofNullable(attributes)) - fun attributes(attributes: Optional) = attributes(attributes.orElse(null)) + /** Alias for calling [Builder.attributes] with `attributes.orElse(null)`. */ + fun attributes(attributes: Optional) = attributes(attributes.getOrNull()) + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun attributes(attributes: JsonField) = apply { this.attributes = attributes } @@ -1741,28 +2503,46 @@ private constructor( /** The contribution currency. */ fun currency(currency: String?) = currency(JsonField.ofNullable(currency)) - /** The contribution currency. */ - fun currency(currency: Optional) = currency(currency.orElse(null)) + /** Alias for calling [Builder.currency] with `currency.orElse(null)`. */ + fun currency(currency: Optional) = currency(currency.getOrNull()) - /** The contribution currency. */ + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } /** The contribution name from the pay statement. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The contribution name from the pay statement. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The contribution name from the pay statement. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } /** Type of benefit. */ fun type(type: BenefitType?) = type(JsonField.ofNullable(type)) - /** Type of benefit. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** Type of benefit. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [BenefitType] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -1784,6 +2564,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [EmployerContribution]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): EmployerContribution = EmployerContribution( amount, @@ -1791,47 +2576,91 @@ private constructor( currency, name, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): EmployerContribution = apply { + if (validated) { + return@apply + } + + amount() + attributes().ifPresent { it.validate() } + currency() + name() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Attributes - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Attributes = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Attributes]. */ @JvmStatic fun builder() = Builder() } @@ -1849,6 +2678,13 @@ private constructor( fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata } fun additionalProperties(additionalProperties: Map) = apply { @@ -1873,56 +2709,90 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Attributes = Attributes(metadata, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Attributes = Attributes(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } - @NoAutoDetect + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + class Metadata - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + /** * The metadata to be attached to the entity by existing rules. It is a key-value * pairs where the values can be of any type (string, number, boolean, object, * array, etc.). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** - * The metadata to be attached to the entity by existing rules. It is a key-value - * pairs where the values can be of any type (string, number, boolean, object, - * array, etc.). + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Metadata]. */ @JvmStatic fun builder() = Builder() } @@ -1946,9 +2816,11 @@ private constructor( fun metadata(metadata: InnerMetadata) = metadata(JsonField.of(metadata)) /** - * The metadata to be attached to the entity by existing rules. It is a - * key-value pairs where the values can be of any type (string, number, boolean, - * object, array, etc.). + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [InnerMetadata] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata @@ -1976,40 +2848,66 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Metadata = Metadata(metadata, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + /** * The metadata to be attached to the entity by existing rules. It is a key-value * pairs where the values can be of any type (string, number, boolean, object, * array, etc.). */ - @NoAutoDetect class InnerMetadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): InnerMetadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [InnerMetadata]. + */ @JvmStatic fun builder() = Builder() } @@ -2046,10 +2944,45 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [InnerMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): InnerMetadata = InnerMetadata(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): InnerMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2211,6 +3144,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): PaymentMethod = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2224,91 +3184,138 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class Tax - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("attributes") - @ExcludeMissing - private val attributes: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("employer") - @ExcludeMissing - private val employer: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val amount: JsonField, + private val attributes: JsonField, + private val currency: JsonField, + private val employer: JsonField, + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The tax amount in cents. */ - fun amount(): Optional = Optional.ofNullable(amount.getNullable("amount")) + @JsonCreator + private constructor( + @JsonProperty("amount") @ExcludeMissing amount: JsonField = JsonMissing.of(), + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("employer") + @ExcludeMissing + employer: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(amount, attributes, currency, employer, name, type, mutableMapOf()) + + /** + * The tax amount in cents. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") - fun attributes(): Optional = - Optional.ofNullable(attributes.getNullable("attributes")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") - /** The currency code. */ - fun currency(): Optional = Optional.ofNullable(currency.getNullable("currency")) + /** + * The currency code. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") - /** `true` if the amount is paid by the employers. */ - fun employer(): Optional = Optional.ofNullable(employer.getNullable("employer")) + /** + * `true` if the amount is paid by the employers. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun employer(): Optional = employer.getOptional("employer") - /** The exact name of tax from the pay statement. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + /** + * The exact name of tax from the pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** The type of taxes. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The type of taxes. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") - /** The tax amount in cents. */ + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("attributes") @ExcludeMissing fun _attributes(): JsonField = attributes - /** The currency code. */ + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency - /** `true` if the amount is paid by the employers. */ + /** + * Returns the raw JSON value of [employer]. + * + * Unlike [employer], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("employer") @ExcludeMissing fun _employer(): JsonField = employer - /** The exact name of tax from the pay statement. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** The type of taxes. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Tax = apply { - if (validated) { - return@apply - } - - amount() - attributes().ifPresent { it.validate() } - currency() - employer() - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Tax]. */ @JvmStatic fun builder() = Builder() } @@ -2337,20 +3344,37 @@ private constructor( /** The tax amount in cents. */ fun amount(amount: Long?) = amount(JsonField.ofNullable(amount)) - /** The tax amount in cents. */ + /** + * Alias for [Builder.amount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun amount(amount: Long) = amount(amount as Long?) - /** The tax amount in cents. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun amount(amount: Optional) = amount(amount.orElse(null) as Long?) + /** Alias for calling [Builder.amount] with `amount.orElse(null)`. */ + fun amount(amount: Optional) = amount(amount.getOrNull()) - /** The tax amount in cents. */ + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun attributes(attributes: Attributes?) = attributes(JsonField.ofNullable(attributes)) - fun attributes(attributes: Optional) = attributes(attributes.orElse(null)) + /** Alias for calling [Builder.attributes] with `attributes.orElse(null)`. */ + fun attributes(attributes: Optional) = attributes(attributes.getOrNull()) + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun attributes(attributes: JsonField) = apply { this.attributes = attributes } @@ -2358,41 +3382,68 @@ private constructor( /** The currency code. */ fun currency(currency: String?) = currency(JsonField.ofNullable(currency)) - /** The currency code. */ - fun currency(currency: Optional) = currency(currency.orElse(null)) + /** Alias for calling [Builder.currency] with `currency.orElse(null)`. */ + fun currency(currency: Optional) = currency(currency.getOrNull()) - /** The currency code. */ + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } /** `true` if the amount is paid by the employers. */ fun employer(employer: Boolean?) = employer(JsonField.ofNullable(employer)) - /** `true` if the amount is paid by the employers. */ + /** + * Alias for [Builder.employer]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun employer(employer: Boolean) = employer(employer as Boolean?) - /** `true` if the amount is paid by the employers. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun employer(employer: Optional) = employer(employer.orElse(null) as Boolean?) + /** Alias for calling [Builder.employer] with `employer.orElse(null)`. */ + fun employer(employer: Optional) = employer(employer.getOrNull()) - /** `true` if the amount is paid by the employers. */ + /** + * Sets [Builder.employer] to an arbitrary JSON value. + * + * You should usually call [Builder.employer] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun employer(employer: JsonField) = apply { this.employer = employer } /** The exact name of tax from the pay statement. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The exact name of tax from the pay statement. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The exact name of tax from the pay statement. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } /** The type of taxes. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** The type of taxes. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** The type of taxes. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -2414,6 +3465,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Tax]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Tax = Tax( amount, @@ -2422,47 +3478,93 @@ private constructor( employer, name, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Tax = apply { + if (validated) { + return@apply + } + + amount() + attributes().ifPresent { it.validate() } + currency() + employer() + name() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (employer.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Attributes - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Attributes = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Attributes]. */ @JvmStatic fun builder() = Builder() } @@ -2480,6 +3582,13 @@ private constructor( fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata } fun additionalProperties(additionalProperties: Map) = apply { @@ -2504,56 +3613,90 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Attributes = Attributes(metadata, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Attributes = Attributes(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } - @NoAutoDetect + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + class Metadata - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + /** * The metadata to be attached to the entity by existing rules. It is a key-value * pairs where the values can be of any type (string, number, boolean, object, * array, etc.). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** - * The metadata to be attached to the entity by existing rules. It is a key-value - * pairs where the values can be of any type (string, number, boolean, object, - * array, etc.). + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Metadata]. */ @JvmStatic fun builder() = Builder() } @@ -2577,9 +3720,11 @@ private constructor( fun metadata(metadata: InnerMetadata) = metadata(JsonField.of(metadata)) /** - * The metadata to be attached to the entity by existing rules. It is a - * key-value pairs where the values can be of any type (string, number, boolean, - * object, array, etc.). + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [InnerMetadata] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata @@ -2607,40 +3752,66 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Metadata = Metadata(metadata, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + /** * The metadata to be attached to the entity by existing rules. It is a key-value * pairs where the values can be of any type (string, number, boolean, object, * array, etc.). */ - @NoAutoDetect class InnerMetadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): InnerMetadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [InnerMetadata]. + */ @JvmStatic fun builder() = Builder() } @@ -2677,10 +3848,45 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [InnerMetadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): InnerMetadata = InnerMetadata(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): InnerMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2835,6 +4041,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2957,6 +4190,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementEvent.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementEvent.kt index 79a6bd0a..7adb6c95 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementEvent.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementEvent.kt @@ -11,57 +11,85 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class PayStatementEvent -@JsonCreator private constructor( - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("data") @ExcludeMissing private val data: JsonField = JsonMissing.of(), - @JsonProperty("event_type") - @ExcludeMissing - private val eventType: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accountId: JsonField, + private val companyId: JsonField, + private val connectionId: JsonField, + private val data: JsonField, + private val eventType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("event_type") + @ExcludeMissing + eventType: JsonField = JsonMissing.of(), + ) : this(accountId, companyId, connectionId, data, eventType, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder() + .accountId(accountId) + .companyId(companyId) + .connectionId(connectionId) + .build() + /** * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") /** * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") - /** Unique Finch ID of the connection associated with the webhook event. */ - fun connectionId(): Optional = - Optional.ofNullable(connectionId.getNullable("connection_id")) + /** + * Unique Finch ID of the connection associated with the webhook event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun connectionId(): Optional = connectionId.getOptional("connection_id") - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") - fun eventType(): Optional = Optional.ofNullable(eventType.getNullable("event_type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun eventType(): Optional = eventType.getOptional("event_type") /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("account_id") @@ -69,53 +97,61 @@ private constructor( fun _accountId(): JsonField = accountId /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [eventType]. + * + * Unlike [eventType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("event_type") @ExcludeMissing fun _eventType(): JsonField = eventType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBaseWebhookEvent(): BaseWebhookEvent = - BaseWebhookEvent.builder() - .accountId(accountId) - .companyId(companyId) - .connectionId(connectionId) - .build() - - private var validated: Boolean = false - - fun validate(): PayStatementEvent = apply { - if (validated) { - return@apply - } - - accountId() - companyId() - connectionId() - data().ifPresent { it.validate() } - eventType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [PayStatementEvent]. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -147,8 +183,11 @@ private constructor( fun accountId(accountId: String) = accountId(JsonField.of(accountId)) /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } @@ -161,8 +200,11 @@ private constructor( fun companyId(companyId: String) = companyId(JsonField.of(companyId)) /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } @@ -170,17 +212,36 @@ private constructor( /** Unique Finch ID of the connection associated with the webhook event. */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } fun data(data: Data) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun eventType(eventType: EventType) = eventType(JsonField.of(eventType)) + /** + * Sets [Builder.eventType] to an arbitrary JSON value. + * + * You should usually call [Builder.eventType] with a well-typed [EventType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun eventType(eventType: JsonField) = apply { this.eventType = eventType } fun additionalProperties(additionalProperties: Map) = apply { @@ -202,6 +263,19 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PayStatementEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): PayStatementEvent = PayStatementEvent( checkRequired("accountId", accountId), @@ -209,59 +283,111 @@ private constructor( connectionId, data, eventType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): PayStatementEvent = apply { + if (validated) { + return@apply + } + + accountId() + companyId() + connectionId() + data().ifPresent { it.validate() } + eventType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountId.asKnown().isPresent) 1 else 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (eventType.asKnown().getOrNull()?.validity() ?: 0) + class Data - @JsonCreator private constructor( - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonProperty("payment_id") - @ExcludeMissing - private val paymentId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val individualId: JsonField, + private val paymentId: JsonField, + private val additionalProperties: MutableMap, ) { - /** The ID of the individual associated with the pay statement. */ - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) + @JsonCreator + private constructor( + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of(), + @JsonProperty("payment_id") + @ExcludeMissing + paymentId: JsonField = JsonMissing.of(), + ) : this(individualId, paymentId, mutableMapOf()) - /** The ID of the payment associated with the pay statement. */ - fun paymentId(): Optional = Optional.ofNullable(paymentId.getNullable("payment_id")) + /** + * The ID of the individual associated with the pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") + + /** + * The ID of the payment associated with the pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun paymentId(): Optional = paymentId.getOptional("payment_id") - /** The ID of the individual associated with the pay statement. */ + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId - /** The ID of the payment associated with the pay statement. */ + /** + * Returns the raw JSON value of [paymentId]. + * + * Unlike [paymentId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("payment_id") @ExcludeMissing fun _paymentId(): JsonField = paymentId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Data = apply { - if (validated) { - return@apply - } - - individualId() - paymentId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Data]. */ @JvmStatic fun builder() = Builder() } @@ -282,7 +408,13 @@ private constructor( /** The ID of the individual associated with the pay statement. */ fun individualId(individualId: String) = individualId(JsonField.of(individualId)) - /** The ID of the individual associated with the pay statement. */ + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -290,7 +422,13 @@ private constructor( /** The ID of the payment associated with the pay statement. */ fun paymentId(paymentId: String) = paymentId(JsonField.of(paymentId)) - /** The ID of the payment associated with the pay statement. */ + /** + * Sets [Builder.paymentId] to an arbitrary JSON value. + * + * You should usually call [Builder.paymentId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun paymentId(paymentId: JsonField) = apply { this.paymentId = paymentId } fun additionalProperties(additionalProperties: Map) = apply { @@ -312,9 +450,45 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Data = Data(individualId, paymentId, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Data = Data(individualId, paymentId, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + individualId() + paymentId() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (individualId.asKnown().isPresent) 1 else 0) + + (if (paymentId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -425,6 +599,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EventType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementItemListResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementItemListResponse.kt new file mode 100644 index 00000000..2e8a895b --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementItemListResponse.kt @@ -0,0 +1,631 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.tryfinch.api.core.Enum +import com.tryfinch.api.core.ExcludeMissing +import com.tryfinch.api.core.JsonField +import com.tryfinch.api.core.JsonMissing +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class PayStatementItemListResponse +private constructor( + private val attributes: JsonField, + private val category: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("category") @ExcludeMissing category: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(attributes, category, name, mutableMapOf()) + + /** + * The attributes of the pay statement item. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") + + /** + * The category of the pay statement item. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun category(): Optional = category.getOptional("category") + + /** + * The name of the pay statement item. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("attributes") + @ExcludeMissing + fun _attributes(): JsonField = attributes + + /** + * Returns the raw JSON value of [category]. + * + * Unlike [category], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("category") @ExcludeMissing fun _category(): JsonField = category + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [PayStatementItemListResponse]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PayStatementItemListResponse]. */ + class Builder internal constructor() { + + private var attributes: JsonField = JsonMissing.of() + private var category: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(payStatementItemListResponse: PayStatementItemListResponse) = apply { + attributes = payStatementItemListResponse.attributes + category = payStatementItemListResponse.category + name = payStatementItemListResponse.name + additionalProperties = payStatementItemListResponse.additionalProperties.toMutableMap() + } + + /** The attributes of the pay statement item. */ + fun attributes(attributes: Attributes) = attributes(JsonField.of(attributes)) + + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun attributes(attributes: JsonField) = apply { this.attributes = attributes } + + /** The category of the pay statement item. */ + fun category(category: Category) = category(JsonField.of(category)) + + /** + * Sets [Builder.category] to an arbitrary JSON value. + * + * You should usually call [Builder.category] with a well-typed [Category] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun category(category: JsonField) = apply { this.category = category } + + /** The name of the pay statement item. */ + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [PayStatementItemListResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): PayStatementItemListResponse = + PayStatementItemListResponse( + attributes, + category, + name, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): PayStatementItemListResponse = apply { + if (validated) { + return@apply + } + + attributes().ifPresent { it.validate() } + category().ifPresent { it.validate() } + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (category.asKnown().getOrNull()?.validity() ?: 0) + + (if (name.asKnown().isPresent) 1 else 0) + + /** The attributes of the pay statement item. */ + class Attributes + private constructor( + private val employer: JsonField, + private val metadata: JsonValue, + private val preTax: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("employer") + @ExcludeMissing + employer: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonValue = JsonMissing.of(), + @JsonProperty("pre_tax") @ExcludeMissing preTax: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(employer, metadata, preTax, type, mutableMapOf()) + + /** + * `true` if the amount is paid by the employers. This field is only available for taxes. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun employer(): Optional = employer.getOptional("employer") + + /** + * The metadata of the pay statement item derived by the rules engine if available. Each + * attribute will be a key-value pair defined by a rule. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonValue = metadata + + /** + * `true` if the pay statement item is pre-tax. This field is only available for employee + * deductions. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun preTax(): Optional = preTax.getOptional("pre_tax") + + /** + * The type of the pay statement item. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [employer]. + * + * Unlike [employer], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("employer") @ExcludeMissing fun _employer(): JsonField = employer + + /** + * Returns the raw JSON value of [preTax]. + * + * Unlike [preTax], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("pre_tax") @ExcludeMissing fun _preTax(): JsonField = preTax + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Attributes]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Attributes]. */ + class Builder internal constructor() { + + private var employer: JsonField = JsonMissing.of() + private var metadata: JsonValue = JsonMissing.of() + private var preTax: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(attributes: Attributes) = apply { + employer = attributes.employer + metadata = attributes.metadata + preTax = attributes.preTax + type = attributes.type + additionalProperties = attributes.additionalProperties.toMutableMap() + } + + /** + * `true` if the amount is paid by the employers. This field is only available for + * taxes. + */ + fun employer(employer: Boolean?) = employer(JsonField.ofNullable(employer)) + + /** + * Alias for [Builder.employer]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun employer(employer: Boolean) = employer(employer as Boolean?) + + /** Alias for calling [Builder.employer] with `employer.orElse(null)`. */ + fun employer(employer: Optional) = employer(employer.getOrNull()) + + /** + * Sets [Builder.employer] to an arbitrary JSON value. + * + * You should usually call [Builder.employer] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun employer(employer: JsonField) = apply { this.employer = employer } + + /** + * The metadata of the pay statement item derived by the rules engine if available. Each + * attribute will be a key-value pair defined by a rule. + */ + fun metadata(metadata: JsonValue) = apply { this.metadata = metadata } + + /** + * `true` if the pay statement item is pre-tax. This field is only available for + * employee deductions. + */ + fun preTax(preTax: Boolean?) = preTax(JsonField.ofNullable(preTax)) + + /** + * Alias for [Builder.preTax]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun preTax(preTax: Boolean) = preTax(preTax as Boolean?) + + /** Alias for calling [Builder.preTax] with `preTax.orElse(null)`. */ + fun preTax(preTax: Optional) = preTax(preTax.getOrNull()) + + /** + * Sets [Builder.preTax] to an arbitrary JSON value. + * + * You should usually call [Builder.preTax] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun preTax(preTax: JsonField) = apply { this.preTax = preTax } + + /** The type of the pay statement item. */ + fun type(type: String?) = type(JsonField.ofNullable(type)) + + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Attributes = + Attributes(employer, metadata, preTax, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + employer() + preTax() + type() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (employer.asKnown().isPresent) 1 else 0) + + (if (preTax.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Attributes && employer == other.employer && metadata == other.metadata && preTax == other.preTax && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(employer, metadata, preTax, type, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Attributes{employer=$employer, metadata=$metadata, preTax=$preTax, type=$type, additionalProperties=$additionalProperties}" + } + + /** The category of the pay statement item. */ + class Category @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val EARNINGS = of("earnings") + + @JvmField val TAXES = of("taxes") + + @JvmField val EMPLOYEE_DEDUCTIONS = of("employee_deductions") + + @JvmField val EMPLOYER_CONTRIBUTIONS = of("employer_contributions") + + @JvmStatic fun of(value: String) = Category(JsonField.of(value)) + } + + /** An enum containing [Category]'s known values. */ + enum class Known { + EARNINGS, + TAXES, + EMPLOYEE_DEDUCTIONS, + EMPLOYER_CONTRIBUTIONS, + } + + /** + * An enum containing [Category]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Category] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + EARNINGS, + TAXES, + EMPLOYEE_DEDUCTIONS, + EMPLOYER_CONTRIBUTIONS, + /** An enum member indicating that [Category] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + EARNINGS -> Value.EARNINGS + TAXES -> Value.TAXES + EMPLOYEE_DEDUCTIONS -> Value.EMPLOYEE_DEDUCTIONS + EMPLOYER_CONTRIBUTIONS -> Value.EMPLOYER_CONTRIBUTIONS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws FinchInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + EARNINGS -> Known.EARNINGS + TAXES -> Known.TAXES + EMPLOYEE_DEDUCTIONS -> Known.EMPLOYEE_DEDUCTIONS + EMPLOYER_CONTRIBUTIONS -> Known.EMPLOYER_CONTRIBUTIONS + else -> throw FinchInvalidDataException("Unknown Category: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws FinchInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): Category = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Category && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is PayStatementItemListResponse && attributes == other.attributes && category == other.category && name == other.name && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(attributes, category, name, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "PayStatementItemListResponse{attributes=$attributes, category=$category, name=$name, additionalProperties=$additionalProperties}" +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementResponse.kt index 22aaf7fe..3f5cf6c6 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementResponse.kt @@ -10,59 +10,83 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class PayStatementResponse -@JsonCreator private constructor( - @JsonProperty("body") - @ExcludeMissing - private val body: JsonField = JsonMissing.of(), - @JsonProperty("code") @ExcludeMissing private val code: JsonField = JsonMissing.of(), - @JsonProperty("payment_id") - @ExcludeMissing - private val paymentId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val body: JsonField, + private val code: JsonField, + private val paymentId: JsonField, + private val additionalProperties: MutableMap, ) { - fun body(): Optional = Optional.ofNullable(body.getNullable("body")) - - fun code(): Optional = Optional.ofNullable(code.getNullable("code")) - - fun paymentId(): Optional = Optional.ofNullable(paymentId.getNullable("payment_id")) - + @JsonCreator + private constructor( + @JsonProperty("body") + @ExcludeMissing + body: JsonField = JsonMissing.of(), + @JsonProperty("code") @ExcludeMissing code: JsonField = JsonMissing.of(), + @JsonProperty("payment_id") @ExcludeMissing paymentId: JsonField = JsonMissing.of(), + ) : this(body, code, paymentId, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun body(): Optional = body.getOptional("body") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun code(): Optional = code.getOptional("code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun paymentId(): Optional = paymentId.getOptional("payment_id") + + /** + * Returns the raw JSON value of [body]. + * + * Unlike [body], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("body") @ExcludeMissing fun _body(): JsonField = body + /** + * Returns the raw JSON value of [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code + /** + * Returns the raw JSON value of [paymentId]. + * + * Unlike [paymentId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("payment_id") @ExcludeMissing fun _paymentId(): JsonField = paymentId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PayStatementResponse = apply { - if (validated) { - return@apply - } - - body().ifPresent { it.validate() } - code() - paymentId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [PayStatementResponse]. */ @JvmStatic fun builder() = Builder() } @@ -84,14 +108,34 @@ private constructor( fun body(body: PayStatementResponseBody) = body(JsonField.of(body)) + /** + * Sets [Builder.body] to an arbitrary JSON value. + * + * You should usually call [Builder.body] with a well-typed [PayStatementResponseBody] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun body(body: JsonField) = apply { this.body = body } fun code(code: Long) = code(JsonField.of(code)) + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun code(code: JsonField) = apply { this.code = code } fun paymentId(paymentId: String) = paymentId(JsonField.of(paymentId)) + /** + * Sets [Builder.paymentId] to an arbitrary JSON value. + * + * You should usually call [Builder.paymentId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun paymentId(paymentId: JsonField) = apply { this.paymentId = paymentId } fun additionalProperties(additionalProperties: Map) = apply { @@ -113,10 +157,47 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PayStatementResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): PayStatementResponse = - PayStatementResponse(body, code, paymentId, additionalProperties.toImmutable()) + PayStatementResponse(body, code, paymentId, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): PayStatementResponse = apply { + if (validated) { + return@apply + } + + body().ifPresent { it.validate() } + code() + paymentId() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (body.asKnown().getOrNull()?.validity() ?: 0) + + (if (code.asKnown().isPresent) 1 else 0) + + (if (paymentId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementResponseBody.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementResponseBody.kt index 4fdae059..66722b9f 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementResponseBody.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayStatementResponseBody.kt @@ -10,58 +10,74 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class PayStatementResponseBody -@JsonCreator private constructor( - @JsonProperty("paging") - @ExcludeMissing - private val paging: JsonField = JsonMissing.of(), - @JsonProperty("pay_statements") - @ExcludeMissing - private val payStatements: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val paging: JsonField, + private val payStatements: JsonField>, + private val additionalProperties: MutableMap, ) { - fun paging(): Optional = Optional.ofNullable(paging.getNullable("paging")) - - /** The array of pay statements for the current payment. */ - fun payStatements(): Optional> = - Optional.ofNullable(payStatements.getNullable("pay_statements")) - + @JsonCreator + private constructor( + @JsonProperty("paging") @ExcludeMissing paging: JsonField = JsonMissing.of(), + @JsonProperty("pay_statements") + @ExcludeMissing + payStatements: JsonField> = JsonMissing.of(), + ) : this(paging, payStatements, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun paging(): Optional = paging.getOptional("paging") + + /** + * The array of pay statements for the current payment. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun payStatements(): Optional> = payStatements.getOptional("pay_statements") + + /** + * Returns the raw JSON value of [paging]. + * + * Unlike [paging], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("paging") @ExcludeMissing fun _paging(): JsonField = paging - /** The array of pay statements for the current payment. */ + /** + * Returns the raw JSON value of [payStatements]. + * + * Unlike [payStatements], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("pay_statements") @ExcludeMissing fun _payStatements(): JsonField> = payStatements + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PayStatementResponseBody = apply { - if (validated) { - return@apply - } - - paging().ifPresent { it.validate() } - payStatements().ifPresent { it.forEach { it.validate() } } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [PayStatementResponseBody]. */ @JvmStatic fun builder() = Builder() } @@ -81,28 +97,38 @@ private constructor( fun paging(paging: Paging) = paging(JsonField.of(paging)) + /** + * Sets [Builder.paging] to an arbitrary JSON value. + * + * You should usually call [Builder.paging] with a well-typed [Paging] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun paging(paging: JsonField) = apply { this.paging = paging } /** The array of pay statements for the current payment. */ fun payStatements(payStatements: List) = payStatements(JsonField.of(payStatements)) - /** The array of pay statements for the current payment. */ + /** + * Sets [Builder.payStatements] to an arbitrary JSON value. + * + * You should usually call [Builder.payStatements] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun payStatements(payStatements: JsonField>) = apply { this.payStatements = payStatements.map { it.toMutableList() } } - /** The array of pay statements for the current payment. */ + /** + * Adds a single [PayStatement] to [payStatements]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addPayStatement(payStatement: PayStatement) = apply { payStatements = - (payStatements ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(payStatement) + (payStatements ?: JsonField.of(mutableListOf())).also { + checkKnown("payStatements", it).add(payStatement) } } @@ -125,14 +151,49 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PayStatementResponseBody]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): PayStatementResponseBody = PayStatementResponseBody( paging, (payStatements ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): PayStatementResponseBody = apply { + if (validated) { + return@apply + } + + paging().ifPresent { it.validate() } + payStatements().ifPresent { it.forEach { it.validate() } } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (paging.asKnown().getOrNull()?.validity() ?: 0) + + (payStatements.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Payment.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Payment.kt index bc5df509..27d85584 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Payment.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Payment.kt @@ -11,160 +11,269 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class Payment -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("company_debit") - @ExcludeMissing - private val companyDebit: JsonField = JsonMissing.of(), - @JsonProperty("debit_date") - @ExcludeMissing - private val debitDate: JsonField = JsonMissing.of(), - @JsonProperty("employee_taxes") - @ExcludeMissing - private val employeeTaxes: JsonField = JsonMissing.of(), - @JsonProperty("employer_taxes") - @ExcludeMissing - private val employerTaxes: JsonField = JsonMissing.of(), - @JsonProperty("gross_pay") - @ExcludeMissing - private val grossPay: JsonField = JsonMissing.of(), - @JsonProperty("individual_ids") - @ExcludeMissing - private val individualIds: JsonField> = JsonMissing.of(), - @JsonProperty("net_pay") - @ExcludeMissing - private val netPay: JsonField = JsonMissing.of(), - @JsonProperty("pay_date") - @ExcludeMissing - private val payDate: JsonField = JsonMissing.of(), - @JsonProperty("pay_frequencies") - @ExcludeMissing - private val payFrequencies: JsonField> = JsonMissing.of(), - @JsonProperty("pay_group_ids") - @ExcludeMissing - private val payGroupIds: JsonField> = JsonMissing.of(), - @JsonProperty("pay_period") - @ExcludeMissing - private val payPeriod: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val companyDebit: JsonField, + private val debitDate: JsonField, + private val employeeTaxes: JsonField, + private val employerTaxes: JsonField, + private val grossPay: JsonField, + private val individualIds: JsonField>, + private val netPay: JsonField, + private val payDate: JsonField, + private val payFrequencies: JsonField>, + private val payGroupIds: JsonField>, + private val payPeriod: JsonField, + private val additionalProperties: MutableMap, ) { - /** The unique id for the payment. */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun companyDebit(): Optional = - Optional.ofNullable(companyDebit.getNullable("company_debit")) - - fun debitDate(): Optional = Optional.ofNullable(debitDate.getNullable("debit_date")) - - fun employeeTaxes(): Optional = - Optional.ofNullable(employeeTaxes.getNullable("employee_taxes")) - - fun employerTaxes(): Optional = - Optional.ofNullable(employerTaxes.getNullable("employer_taxes")) - - fun grossPay(): Optional = Optional.ofNullable(grossPay.getNullable("gross_pay")) - - /** Array of every individual on this payment. */ - fun individualIds(): Optional> = - Optional.ofNullable(individualIds.getNullable("individual_ids")) - - fun netPay(): Optional = Optional.ofNullable(netPay.getNullable("net_pay")) - - fun payDate(): Optional = Optional.ofNullable(payDate.getNullable("pay_date")) - - /** List of pay frequencies associated with this payment. */ + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("company_debit") + @ExcludeMissing + companyDebit: JsonField = JsonMissing.of(), + @JsonProperty("debit_date") @ExcludeMissing debitDate: JsonField = JsonMissing.of(), + @JsonProperty("employee_taxes") + @ExcludeMissing + employeeTaxes: JsonField = JsonMissing.of(), + @JsonProperty("employer_taxes") + @ExcludeMissing + employerTaxes: JsonField = JsonMissing.of(), + @JsonProperty("gross_pay") @ExcludeMissing grossPay: JsonField = JsonMissing.of(), + @JsonProperty("individual_ids") + @ExcludeMissing + individualIds: JsonField> = JsonMissing.of(), + @JsonProperty("net_pay") @ExcludeMissing netPay: JsonField = JsonMissing.of(), + @JsonProperty("pay_date") @ExcludeMissing payDate: JsonField = JsonMissing.of(), + @JsonProperty("pay_frequencies") + @ExcludeMissing + payFrequencies: JsonField> = JsonMissing.of(), + @JsonProperty("pay_group_ids") + @ExcludeMissing + payGroupIds: JsonField> = JsonMissing.of(), + @JsonProperty("pay_period") + @ExcludeMissing + payPeriod: JsonField = JsonMissing.of(), + ) : this( + id, + companyDebit, + debitDate, + employeeTaxes, + employerTaxes, + grossPay, + individualIds, + netPay, + payDate, + payFrequencies, + payGroupIds, + payPeriod, + mutableMapOf(), + ) + + /** + * The unique id for the payment. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun companyDebit(): Optional = companyDebit.getOptional("company_debit") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun debitDate(): Optional = debitDate.getOptional("debit_date") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun employeeTaxes(): Optional = employeeTaxes.getOptional("employee_taxes") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun employerTaxes(): Optional = employerTaxes.getOptional("employer_taxes") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun grossPay(): Optional = grossPay.getOptional("gross_pay") + + /** + * Array of every individual on this payment. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualIds(): Optional> = individualIds.getOptional("individual_ids") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun netPay(): Optional = netPay.getOptional("net_pay") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun payDate(): Optional = payDate.getOptional("pay_date") + + /** + * List of pay frequencies associated with this payment. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun payFrequencies(): Optional> = - Optional.ofNullable(payFrequencies.getNullable("pay_frequencies")) - - /** Array of the Finch id (uuidv4) of every pay group associated with this payment. */ - fun payGroupIds(): Optional> = - Optional.ofNullable(payGroupIds.getNullable("pay_group_ids")) - - /** The pay period object. */ - fun payPeriod(): Optional = Optional.ofNullable(payPeriod.getNullable("pay_period")) - - /** The unique id for the payment. */ + payFrequencies.getOptional("pay_frequencies") + + /** + * Array of the Finch id (uuidv4) of every pay group associated with this payment. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun payGroupIds(): Optional> = payGroupIds.getOptional("pay_group_ids") + + /** + * The pay period object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun payPeriod(): Optional = payPeriod.getOptional("pay_period") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [companyDebit]. + * + * Unlike [companyDebit], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("company_debit") @ExcludeMissing fun _companyDebit(): JsonField = companyDebit + /** + * Returns the raw JSON value of [debitDate]. + * + * Unlike [debitDate], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("debit_date") @ExcludeMissing fun _debitDate(): JsonField = debitDate + /** + * Returns the raw JSON value of [employeeTaxes]. + * + * Unlike [employeeTaxes], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("employee_taxes") @ExcludeMissing fun _employeeTaxes(): JsonField = employeeTaxes + /** + * Returns the raw JSON value of [employerTaxes]. + * + * Unlike [employerTaxes], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("employer_taxes") @ExcludeMissing fun _employerTaxes(): JsonField = employerTaxes + /** + * Returns the raw JSON value of [grossPay]. + * + * Unlike [grossPay], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("gross_pay") @ExcludeMissing fun _grossPay(): JsonField = grossPay - /** Array of every individual on this payment. */ + /** + * Returns the raw JSON value of [individualIds]. + * + * Unlike [individualIds], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("individual_ids") @ExcludeMissing fun _individualIds(): JsonField> = individualIds + /** + * Returns the raw JSON value of [netPay]. + * + * Unlike [netPay], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("net_pay") @ExcludeMissing fun _netPay(): JsonField = netPay + /** + * Returns the raw JSON value of [payDate]. + * + * Unlike [payDate], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("pay_date") @ExcludeMissing fun _payDate(): JsonField = payDate - /** List of pay frequencies associated with this payment. */ + /** + * Returns the raw JSON value of [payFrequencies]. + * + * Unlike [payFrequencies], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("pay_frequencies") @ExcludeMissing fun _payFrequencies(): JsonField> = payFrequencies - /** Array of the Finch id (uuidv4) of every pay group associated with this payment. */ + /** + * Returns the raw JSON value of [payGroupIds]. + * + * Unlike [payGroupIds], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("pay_group_ids") @ExcludeMissing fun _payGroupIds(): JsonField> = payGroupIds - /** The pay period object. */ + /** + * Returns the raw JSON value of [payPeriod]. + * + * Unlike [payPeriod], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("pay_period") @ExcludeMissing fun _payPeriod(): JsonField = payPeriod + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Payment = apply { - if (validated) { - return@apply - } - - id() - companyDebit().ifPresent { it.validate() } - debitDate() - employeeTaxes().ifPresent { it.validate() } - employerTaxes().ifPresent { it.validate() } - grossPay().ifPresent { it.validate() } - individualIds() - netPay().ifPresent { it.validate() } - payDate() - payFrequencies() - payGroupIds() - payPeriod().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Payment]. */ @JvmStatic fun builder() = Builder() } @@ -205,29 +314,57 @@ private constructor( /** The unique id for the payment. */ fun id(id: String) = id(JsonField.of(id)) - /** The unique id for the payment. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun companyDebit(companyDebit: Money?) = companyDebit(JsonField.ofNullable(companyDebit)) - fun companyDebit(companyDebit: Optional) = companyDebit(companyDebit.orElse(null)) + /** Alias for calling [Builder.companyDebit] with `companyDebit.orElse(null)`. */ + fun companyDebit(companyDebit: Optional) = companyDebit(companyDebit.getOrNull()) + /** + * Sets [Builder.companyDebit] to an arbitrary JSON value. + * + * You should usually call [Builder.companyDebit] with a well-typed [Money] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun companyDebit(companyDebit: JsonField) = apply { this.companyDebit = companyDebit } fun debitDate(debitDate: String?) = debitDate(JsonField.ofNullable(debitDate)) - fun debitDate(debitDate: Optional) = debitDate(debitDate.orElse(null)) + /** Alias for calling [Builder.debitDate] with `debitDate.orElse(null)`. */ + fun debitDate(debitDate: Optional) = debitDate(debitDate.getOrNull()) + /** + * Sets [Builder.debitDate] to an arbitrary JSON value. + * + * You should usually call [Builder.debitDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun debitDate(debitDate: JsonField) = apply { this.debitDate = debitDate } fun employeeTaxes(employeeTaxes: Money?) = employeeTaxes(JsonField.ofNullable(employeeTaxes)) - fun employeeTaxes(employeeTaxes: Optional) = - employeeTaxes(employeeTaxes.orElse(null)) + /** Alias for calling [Builder.employeeTaxes] with `employeeTaxes.orElse(null)`. */ + fun employeeTaxes(employeeTaxes: Optional) = employeeTaxes(employeeTaxes.getOrNull()) + /** + * Sets [Builder.employeeTaxes] to an arbitrary JSON value. + * + * You should usually call [Builder.employeeTaxes] with a well-typed [Money] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun employeeTaxes(employeeTaxes: JsonField) = apply { this.employeeTaxes = employeeTaxes } @@ -235,117 +372,163 @@ private constructor( fun employerTaxes(employerTaxes: Money?) = employerTaxes(JsonField.ofNullable(employerTaxes)) - fun employerTaxes(employerTaxes: Optional) = - employerTaxes(employerTaxes.orElse(null)) + /** Alias for calling [Builder.employerTaxes] with `employerTaxes.orElse(null)`. */ + fun employerTaxes(employerTaxes: Optional) = employerTaxes(employerTaxes.getOrNull()) + /** + * Sets [Builder.employerTaxes] to an arbitrary JSON value. + * + * You should usually call [Builder.employerTaxes] with a well-typed [Money] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun employerTaxes(employerTaxes: JsonField) = apply { this.employerTaxes = employerTaxes } fun grossPay(grossPay: Money?) = grossPay(JsonField.ofNullable(grossPay)) - fun grossPay(grossPay: Optional) = grossPay(grossPay.orElse(null)) + /** Alias for calling [Builder.grossPay] with `grossPay.orElse(null)`. */ + fun grossPay(grossPay: Optional) = grossPay(grossPay.getOrNull()) + /** + * Sets [Builder.grossPay] to an arbitrary JSON value. + * + * You should usually call [Builder.grossPay] with a well-typed [Money] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun grossPay(grossPay: JsonField) = apply { this.grossPay = grossPay } /** Array of every individual on this payment. */ fun individualIds(individualIds: List?) = individualIds(JsonField.ofNullable(individualIds)) - /** Array of every individual on this payment. */ + /** Alias for calling [Builder.individualIds] with `individualIds.orElse(null)`. */ fun individualIds(individualIds: Optional>) = - individualIds(individualIds.orElse(null)) + individualIds(individualIds.getOrNull()) - /** Array of every individual on this payment. */ + /** + * Sets [Builder.individualIds] to an arbitrary JSON value. + * + * You should usually call [Builder.individualIds] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun individualIds(individualIds: JsonField>) = apply { this.individualIds = individualIds.map { it.toMutableList() } } - /** Array of every individual on this payment. */ + /** + * Adds a single [String] to [individualIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addIndividualId(individualId: String) = apply { individualIds = - (individualIds ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(individualId) + (individualIds ?: JsonField.of(mutableListOf())).also { + checkKnown("individualIds", it).add(individualId) } } fun netPay(netPay: Money?) = netPay(JsonField.ofNullable(netPay)) - fun netPay(netPay: Optional) = netPay(netPay.orElse(null)) + /** Alias for calling [Builder.netPay] with `netPay.orElse(null)`. */ + fun netPay(netPay: Optional) = netPay(netPay.getOrNull()) + /** + * Sets [Builder.netPay] to an arbitrary JSON value. + * + * You should usually call [Builder.netPay] with a well-typed [Money] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun netPay(netPay: JsonField) = apply { this.netPay = netPay } fun payDate(payDate: String?) = payDate(JsonField.ofNullable(payDate)) - fun payDate(payDate: Optional) = payDate(payDate.orElse(null)) + /** Alias for calling [Builder.payDate] with `payDate.orElse(null)`. */ + fun payDate(payDate: Optional) = payDate(payDate.getOrNull()) + /** + * Sets [Builder.payDate] to an arbitrary JSON value. + * + * You should usually call [Builder.payDate] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun payDate(payDate: JsonField) = apply { this.payDate = payDate } /** List of pay frequencies associated with this payment. */ fun payFrequencies(payFrequencies: List?) = payFrequencies(JsonField.ofNullable(payFrequencies)) - /** List of pay frequencies associated with this payment. */ + /** Alias for calling [Builder.payFrequencies] with `payFrequencies.orElse(null)`. */ fun payFrequencies(payFrequencies: Optional>) = - payFrequencies(payFrequencies.orElse(null)) + payFrequencies(payFrequencies.getOrNull()) - /** List of pay frequencies associated with this payment. */ + /** + * Sets [Builder.payFrequencies] to an arbitrary JSON value. + * + * You should usually call [Builder.payFrequencies] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun payFrequencies(payFrequencies: JsonField>) = apply { this.payFrequencies = payFrequencies.map { it.toMutableList() } } - /** List of pay frequencies associated with this payment. */ + /** + * Adds a single [PayFrequency] to [payFrequencies]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addPayFrequency(payFrequency: PayFrequency) = apply { payFrequencies = - (payFrequencies ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(payFrequency) + (payFrequencies ?: JsonField.of(mutableListOf())).also { + checkKnown("payFrequencies", it).add(payFrequency) } } /** Array of the Finch id (uuidv4) of every pay group associated with this payment. */ fun payGroupIds(payGroupIds: List?) = payGroupIds(JsonField.ofNullable(payGroupIds)) - /** Array of the Finch id (uuidv4) of every pay group associated with this payment. */ - fun payGroupIds(payGroupIds: Optional>) = payGroupIds(payGroupIds.orElse(null)) + /** Alias for calling [Builder.payGroupIds] with `payGroupIds.orElse(null)`. */ + fun payGroupIds(payGroupIds: Optional>) = payGroupIds(payGroupIds.getOrNull()) - /** Array of the Finch id (uuidv4) of every pay group associated with this payment. */ + /** + * Sets [Builder.payGroupIds] to an arbitrary JSON value. + * + * You should usually call [Builder.payGroupIds] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun payGroupIds(payGroupIds: JsonField>) = apply { this.payGroupIds = payGroupIds.map { it.toMutableList() } } - /** Array of the Finch id (uuidv4) of every pay group associated with this payment. */ + /** + * Adds a single [String] to [payGroupIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addPayGroupId(payGroupId: String) = apply { payGroupIds = - (payGroupIds ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(payGroupId) + (payGroupIds ?: JsonField.of(mutableListOf())).also { + checkKnown("payGroupIds", it).add(payGroupId) } } /** The pay period object. */ fun payPeriod(payPeriod: PayPeriod?) = payPeriod(JsonField.ofNullable(payPeriod)) - /** The pay period object. */ - fun payPeriod(payPeriod: Optional) = payPeriod(payPeriod.orElse(null)) + /** Alias for calling [Builder.payPeriod] with `payPeriod.orElse(null)`. */ + fun payPeriod(payPeriod: Optional) = payPeriod(payPeriod.getOrNull()) - /** The pay period object. */ + /** + * Sets [Builder.payPeriod] to an arbitrary JSON value. + * + * You should usually call [Builder.payPeriod] with a well-typed [PayPeriod] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun payPeriod(payPeriod: JsonField) = apply { this.payPeriod = payPeriod } fun additionalProperties(additionalProperties: Map) = apply { @@ -367,6 +550,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Payment]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Payment = Payment( id, @@ -381,10 +569,60 @@ private constructor( (payFrequencies ?: JsonMissing.of()).map { it.toImmutable() }, (payGroupIds ?: JsonMissing.of()).map { it.toImmutable() }, payPeriod, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Payment = apply { + if (validated) { + return@apply + } + + id() + companyDebit().ifPresent { it.validate() } + debitDate() + employeeTaxes().ifPresent { it.validate() } + employerTaxes().ifPresent { it.validate() } + grossPay().ifPresent { it.validate() } + individualIds() + netPay().ifPresent { it.validate() } + payDate() + payFrequencies().ifPresent { it.forEach { it.validate() } } + payGroupIds() + payPeriod().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (companyDebit.asKnown().getOrNull()?.validity() ?: 0) + + (if (debitDate.asKnown().isPresent) 1 else 0) + + (employeeTaxes.asKnown().getOrNull()?.validity() ?: 0) + + (employerTaxes.asKnown().getOrNull()?.validity() ?: 0) + + (grossPay.asKnown().getOrNull()?.validity() ?: 0) + + (individualIds.asKnown().getOrNull()?.size ?: 0) + + (netPay.asKnown().getOrNull()?.validity() ?: 0) + + (if (payDate.asKnown().isPresent) 1 else 0) + + (payFrequencies.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (payGroupIds.asKnown().getOrNull()?.size ?: 0) + + (payPeriod.asKnown().getOrNull()?.validity() ?: 0) + class PayFrequency @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -514,6 +752,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): PayFrequency = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -528,48 +793,62 @@ private constructor( } /** The pay period object. */ - @NoAutoDetect class PayPeriod - @JsonCreator private constructor( - @JsonProperty("end_date") - @ExcludeMissing - private val endDate: JsonField = JsonMissing.of(), - @JsonProperty("start_date") - @ExcludeMissing - private val startDate: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val endDate: JsonField, + private val startDate: JsonField, + private val additionalProperties: MutableMap, ) { - fun endDate(): Optional = Optional.ofNullable(endDate.getNullable("end_date")) + @JsonCreator + private constructor( + @JsonProperty("end_date") @ExcludeMissing endDate: JsonField = JsonMissing.of(), + @JsonProperty("start_date") + @ExcludeMissing + startDate: JsonField = JsonMissing.of(), + ) : this(endDate, startDate, mutableMapOf()) - fun startDate(): Optional = Optional.ofNullable(startDate.getNullable("start_date")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun endDate(): Optional = endDate.getOptional("end_date") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun startDate(): Optional = startDate.getOptional("start_date") + /** + * Returns the raw JSON value of [endDate]. + * + * Unlike [endDate], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("end_date") @ExcludeMissing fun _endDate(): JsonField = endDate + /** + * Returns the raw JSON value of [startDate]. + * + * Unlike [startDate], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("start_date") @ExcludeMissing fun _startDate(): JsonField = startDate + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PayPeriod = apply { - if (validated) { - return@apply - } - - endDate() - startDate() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [PayPeriod]. */ @JvmStatic fun builder() = Builder() } @@ -589,14 +868,30 @@ private constructor( fun endDate(endDate: String?) = endDate(JsonField.ofNullable(endDate)) - fun endDate(endDate: Optional) = endDate(endDate.orElse(null)) + /** Alias for calling [Builder.endDate] with `endDate.orElse(null)`. */ + fun endDate(endDate: Optional) = endDate(endDate.getOrNull()) + /** + * Sets [Builder.endDate] to an arbitrary JSON value. + * + * You should usually call [Builder.endDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun endDate(endDate: JsonField) = apply { this.endDate = endDate } fun startDate(startDate: String?) = startDate(JsonField.ofNullable(startDate)) - fun startDate(startDate: Optional) = startDate(startDate.orElse(null)) + /** Alias for calling [Builder.startDate] with `startDate.orElse(null)`. */ + fun startDate(startDate: Optional) = startDate(startDate.getOrNull()) + /** + * Sets [Builder.startDate] to an arbitrary JSON value. + * + * You should usually call [Builder.startDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun startDate(startDate: JsonField) = apply { this.startDate = startDate } fun additionalProperties(additionalProperties: Map) = apply { @@ -618,10 +913,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PayPeriod]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): PayPeriod = - PayPeriod(endDate, startDate, additionalProperties.toImmutable()) + PayPeriod(endDate, startDate, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): PayPeriod = apply { + if (validated) { + return@apply + } + + endDate() + startDate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (endDate.asKnown().isPresent) 1 else 0) + + (if (startDate.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PaymentCreateResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PaymentCreateResponse.kt index 72337ed1..9504615b 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PaymentCreateResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PaymentCreateResponse.kt @@ -10,57 +10,77 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects -@NoAutoDetect class PaymentCreateResponse -@JsonCreator private constructor( - @JsonProperty("pay_date") - @ExcludeMissing - private val payDate: JsonField = JsonMissing.of(), - @JsonProperty("payment_id") - @ExcludeMissing - private val paymentId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val payDate: JsonField, + private val paymentId: JsonField, + private val additionalProperties: MutableMap, ) { - /** The date of the payment. */ + @JsonCreator + private constructor( + @JsonProperty("pay_date") @ExcludeMissing payDate: JsonField = JsonMissing.of(), + @JsonProperty("payment_id") @ExcludeMissing paymentId: JsonField = JsonMissing.of(), + ) : this(payDate, paymentId, mutableMapOf()) + + /** + * The date of the payment. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun payDate(): String = payDate.getRequired("pay_date") - /** The ID of the payment. */ + /** + * The ID of the payment. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun paymentId(): String = paymentId.getRequired("payment_id") - /** The date of the payment. */ + /** + * Returns the raw JSON value of [payDate]. + * + * Unlike [payDate], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("pay_date") @ExcludeMissing fun _payDate(): JsonField = payDate - /** The ID of the payment. */ + /** + * Returns the raw JSON value of [paymentId]. + * + * Unlike [paymentId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("payment_id") @ExcludeMissing fun _paymentId(): JsonField = paymentId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PaymentCreateResponse = apply { - if (validated) { - return@apply - } - - payDate() - paymentId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [PaymentCreateResponse]. + * + * The following fields are required: + * ```java + * .payDate() + * .paymentId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -81,13 +101,24 @@ private constructor( /** The date of the payment. */ fun payDate(payDate: String) = payDate(JsonField.of(payDate)) - /** The date of the payment. */ + /** + * Sets [Builder.payDate] to an arbitrary JSON value. + * + * You should usually call [Builder.payDate] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun payDate(payDate: JsonField) = apply { this.payDate = payDate } /** The ID of the payment. */ fun paymentId(paymentId: String) = paymentId(JsonField.of(paymentId)) - /** The ID of the payment. */ + /** + * Sets [Builder.paymentId] to an arbitrary JSON value. + * + * You should usually call [Builder.paymentId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun paymentId(paymentId: JsonField) = apply { this.paymentId = paymentId } fun additionalProperties(additionalProperties: Map) = apply { @@ -109,14 +140,56 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PaymentCreateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .payDate() + * .paymentId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): PaymentCreateResponse = PaymentCreateResponse( checkRequired("payDate", payDate), checkRequired("paymentId", paymentId), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): PaymentCreateResponse = apply { + if (validated) { + return@apply + } + + payDate() + paymentId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (payDate.asKnown().isPresent) 1 else 0) + (if (paymentId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PaymentEvent.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PaymentEvent.kt index dcd964b3..aa2542ff 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PaymentEvent.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PaymentEvent.kt @@ -11,59 +11,87 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class PaymentEvent -@JsonCreator private constructor( - @JsonProperty("account_id") - @ExcludeMissing - private val accountId: JsonField = JsonMissing.of(), - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("connection_id") - @ExcludeMissing - private val connectionId: JsonField = JsonMissing.of(), - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("event_type") - @ExcludeMissing - private val eventType: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val accountId: JsonField, + private val companyId: JsonField, + private val connectionId: JsonField, + private val data: JsonField, + private val eventType: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("account_id") @ExcludeMissing accountId: JsonField = JsonMissing.of(), + @JsonProperty("company_id") @ExcludeMissing companyId: JsonField = JsonMissing.of(), + @JsonProperty("connection_id") + @ExcludeMissing + connectionId: JsonField = JsonMissing.of(), + @JsonProperty("data") + @ExcludeMissing + data: JsonField = JsonMissing.of(), + @JsonProperty("event_type") + @ExcludeMissing + eventType: JsonField = JsonMissing.of(), + ) : this(accountId, companyId, connectionId, data, eventType, mutableMapOf()) + + fun toBaseWebhookEvent(): BaseWebhookEvent = + BaseWebhookEvent.builder() + .accountId(accountId) + .companyId(companyId) + .connectionId(connectionId) + .build() + /** * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun accountId(): String = accountId.getRequired("account_id") /** * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use * `connection_id` instead to identify the connection associated with this event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ @Deprecated("deprecated") fun companyId(): String = companyId.getRequired("company_id") - /** Unique Finch ID of the connection associated with the webhook event. */ - fun connectionId(): Optional = - Optional.ofNullable(connectionId.getNullable("connection_id")) + /** + * Unique Finch ID of the connection associated with the webhook event. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun connectionId(): Optional = connectionId.getOptional("connection_id") - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") - fun eventType(): Optional = Optional.ofNullable(eventType.getNullable("event_type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun eventType(): Optional = eventType.getOptional("event_type") /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [accountId]. + * + * Unlike [accountId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("account_id") @@ -71,53 +99,61 @@ private constructor( fun _accountId(): JsonField = accountId /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. */ @Deprecated("deprecated") @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Returns the raw JSON value of [connectionId]. + * + * Unlike [connectionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connection_id") @ExcludeMissing fun _connectionId(): JsonField = connectionId + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [eventType]. + * + * Unlike [eventType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("event_type") @ExcludeMissing fun _eventType(): JsonField = eventType + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBaseWebhookEvent(): BaseWebhookEvent = - BaseWebhookEvent.builder() - .accountId(accountId) - .companyId(companyId) - .connectionId(connectionId) - .build() - - private var validated: Boolean = false - - fun validate(): PaymentEvent = apply { - if (validated) { - return@apply - } - - accountId() - companyId() - connectionId() - data().ifPresent { it.validate() } - eventType() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [PaymentEvent]. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -149,8 +185,11 @@ private constructor( fun accountId(accountId: String) = accountId(JsonField.of(accountId)) /** - * [DEPRECATED] Unique Finch ID of the employer account used to make this connection. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.accountId] to an arbitrary JSON value. + * + * You should usually call [Builder.accountId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun accountId(accountId: JsonField) = apply { this.accountId = accountId } @@ -163,8 +202,11 @@ private constructor( fun companyId(companyId: String) = companyId(JsonField.of(companyId)) /** - * [DEPRECATED] Unique Finch ID of the company for which data has been updated. Use - * `connection_id` instead to identify the connection associated with this event. + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ @Deprecated("deprecated") fun companyId(companyId: JsonField) = apply { this.companyId = companyId } @@ -172,17 +214,37 @@ private constructor( /** Unique Finch ID of the connection associated with the webhook event. */ fun connectionId(connectionId: String) = connectionId(JsonField.of(connectionId)) - /** Unique Finch ID of the connection associated with the webhook event. */ + /** + * Sets [Builder.connectionId] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectionId(connectionId: JsonField) = apply { this.connectionId = connectionId } fun data(data: PaymentIdentifiers) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [PaymentIdentifiers] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun eventType(eventType: EventType) = eventType(JsonField.of(eventType)) + /** + * Sets [Builder.eventType] to an arbitrary JSON value. + * + * You should usually call [Builder.eventType] with a well-typed [EventType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun eventType(eventType: JsonField) = apply { this.eventType = eventType } fun additionalProperties(additionalProperties: Map) = apply { @@ -204,6 +266,19 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PaymentEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accountId() + * .companyId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): PaymentEvent = PaymentEvent( checkRequired("accountId", accountId), @@ -211,56 +286,114 @@ private constructor( connectionId, data, eventType, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): PaymentEvent = apply { + if (validated) { + return@apply + } + + accountId() + companyId() + connectionId() + data().ifPresent { it.validate() } + eventType().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountId.asKnown().isPresent) 1 else 0) + + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (connectionId.asKnown().isPresent) 1 else 0) + + (data.asKnown().getOrNull()?.validity() ?: 0) + + (eventType.asKnown().getOrNull()?.validity() ?: 0) + class PaymentIdentifiers - @JsonCreator private constructor( - @JsonProperty("pay_date") - @ExcludeMissing - private val payDate: JsonField = JsonMissing.of(), - @JsonProperty("payment_id") - @ExcludeMissing - private val paymentId: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val payDate: JsonField, + private val paymentId: JsonField, + private val additionalProperties: MutableMap, ) { - /** The date of the payment. */ + @JsonCreator + private constructor( + @JsonProperty("pay_date") @ExcludeMissing payDate: JsonField = JsonMissing.of(), + @JsonProperty("payment_id") + @ExcludeMissing + paymentId: JsonField = JsonMissing.of(), + ) : this(payDate, paymentId, mutableMapOf()) + + /** + * The date of the payment. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ fun payDate(): String = payDate.getRequired("pay_date") - /** The ID of the payment. */ + /** + * The ID of the payment. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ fun paymentId(): String = paymentId.getRequired("payment_id") - /** The date of the payment. */ + /** + * Returns the raw JSON value of [payDate]. + * + * Unlike [payDate], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("pay_date") @ExcludeMissing fun _payDate(): JsonField = payDate - /** The ID of the payment. */ + /** + * Returns the raw JSON value of [paymentId]. + * + * Unlike [paymentId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("payment_id") @ExcludeMissing fun _paymentId(): JsonField = paymentId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PaymentIdentifiers = apply { - if (validated) { - return@apply - } - - payDate() - paymentId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [PaymentIdentifiers]. + * + * The following fields are required: + * ```java + * .payDate() + * .paymentId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -281,13 +414,25 @@ private constructor( /** The date of the payment. */ fun payDate(payDate: String) = payDate(JsonField.of(payDate)) - /** The date of the payment. */ + /** + * Sets [Builder.payDate] to an arbitrary JSON value. + * + * You should usually call [Builder.payDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun payDate(payDate: JsonField) = apply { this.payDate = payDate } /** The ID of the payment. */ fun paymentId(paymentId: String) = paymentId(JsonField.of(paymentId)) - /** The ID of the payment. */ + /** + * Sets [Builder.paymentId] to an arbitrary JSON value. + * + * You should usually call [Builder.paymentId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun paymentId(paymentId: JsonField) = apply { this.paymentId = paymentId } fun additionalProperties(additionalProperties: Map) = apply { @@ -309,14 +454,58 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PaymentIdentifiers]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .payDate() + * .paymentId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): PaymentIdentifiers = PaymentIdentifiers( checkRequired("payDate", payDate), checkRequired("paymentId", paymentId), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): PaymentIdentifiers = apply { + if (validated) { + return@apply + } + + payDate() + paymentId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (payDate.asKnown().isPresent) 1 else 0) + + (if (paymentId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -427,6 +616,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EventType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupListPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupListPage.kt index aec5d816..45c9b544 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupListPage.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupListPage.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.blocking.payroll.PayGroupService +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull /** Read company pay groups and frequencies */ class PayrollPayGroupListPage @@ -68,24 +68,30 @@ private constructor( ) = PayrollPayGroupListPage(payGroupsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -98,6 +104,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -115,6 +129,9 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of [PayrollPayGroupListPage]. + */ @JvmStatic fun builder() = Builder() } @@ -137,7 +154,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } @@ -151,7 +173,7 @@ private constructor( while (index < page.items().size) { yield(page.items()[index++]) } - page = page.getNextPage().orElse(null) ?: break + page = page.getNextPage().getOrNull() ?: break index = 0 } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupListPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupListPageAsync.kt index 8e352508..d280c90d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupListPageAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupListPageAsync.kt @@ -10,15 +10,15 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.async.payroll.PayGroupServiceAsync +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull /** Read company pay groups and frequencies */ class PayrollPayGroupListPageAsync @@ -71,24 +71,30 @@ private constructor( ) = PayrollPayGroupListPageAsync(payGroupsService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") - private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -101,6 +107,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -118,6 +132,10 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of + * [PayrollPayGroupListPageAsync]. + */ @JvmStatic fun builder() = Builder() } @@ -140,7 +158,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupListParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupListParams.kt index 0b6a7c84..327b9204 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupListParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupListParams.kt @@ -2,13 +2,13 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams import com.tryfinch.api.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Read company pay groups and frequencies */ class PayrollPayGroupListParams @@ -27,27 +27,19 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams { - val queryParams = QueryParams.builder() - this.individualId?.let { queryParams.put("individual_id", listOf(it.toString())) } - this.payFrequencies?.let { queryParams.put("pay_frequencies[]", it.map(Any::toString)) } - queryParams.putAll(additionalQueryParams) - return queryParams.build() - } - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): PayrollPayGroupListParams = builder().build() + /** + * Returns a mutable builder for constructing an instance of [PayrollPayGroupListParams]. + */ @JvmStatic fun builder() = Builder() } /** A builder for [PayrollPayGroupListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var individualId: String? = null @@ -65,15 +57,22 @@ private constructor( fun individualId(individualId: String?) = apply { this.individualId = individualId } - fun individualId(individualId: Optional) = individualId(individualId.orElse(null)) + /** Alias for calling [Builder.individualId] with `individualId.orElse(null)`. */ + fun individualId(individualId: Optional) = individualId(individualId.getOrNull()) fun payFrequencies(payFrequencies: List?) = apply { this.payFrequencies = payFrequencies?.toMutableList() } + /** Alias for calling [Builder.payFrequencies] with `payFrequencies.orElse(null)`. */ fun payFrequencies(payFrequencies: Optional>) = - payFrequencies(payFrequencies.orElse(null)) + payFrequencies(payFrequencies.getOrNull()) + /** + * Adds a single [String] to [payFrequencies]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addPayFrequency(payFrequency: String) = apply { payFrequencies = (payFrequencies ?: mutableListOf()).apply { add(payFrequency) } } @@ -176,6 +175,11 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [PayrollPayGroupListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): PayrollPayGroupListParams = PayrollPayGroupListParams( individualId, @@ -185,6 +189,17 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + individualId?.let { put("individual_id", it) } + payFrequencies?.forEach { put("pay_frequencies[]", it) } + putAll(additionalQueryParams) + } + .build() + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupRetrieveParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupRetrieveParams.kt index e78ff6a9..129a9287 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupRetrieveParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/PayrollPayGroupRetrieveParams.kt @@ -2,7 +2,6 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers @@ -23,26 +22,23 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> payGroupId - else -> "" - } - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [PayrollPayGroupRetrieveParams]. + * + * The following fields are required: + * ```java + * .payGroupId() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [PayrollPayGroupRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var payGroupId: String? = null @@ -156,6 +152,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [PayrollPayGroupRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .payGroupId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): PayrollPayGroupRetrieveParams = PayrollPayGroupRetrieveParams( checkRequired("payGroupId", payGroupId), @@ -164,6 +172,16 @@ private constructor( ) } + fun _pathParam(index: Int): String = + when (index) { + 0 -> payGroupId + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Provider.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Provider.kt index ea274b56..1c055bf2 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Provider.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/Provider.kt @@ -11,151 +11,243 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class Provider -@JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonProperty("authentication_methods") - @ExcludeMissing - private val authenticationMethods: JsonField> = JsonMissing.of(), - @JsonProperty("beta") @ExcludeMissing private val beta: JsonField = JsonMissing.of(), - @JsonProperty("display_name") - @ExcludeMissing - private val displayName: JsonField = JsonMissing.of(), - @JsonProperty("icon") @ExcludeMissing private val icon: JsonField = JsonMissing.of(), - @JsonProperty("logo") @ExcludeMissing private val logo: JsonField = JsonMissing.of(), - @JsonProperty("manual") - @ExcludeMissing - private val manual: JsonField = JsonMissing.of(), - @JsonProperty("mfa_required") - @ExcludeMissing - private val mfaRequired: JsonField = JsonMissing.of(), - @JsonProperty("primary_color") - @ExcludeMissing - private val primaryColor: JsonField = JsonMissing.of(), - @JsonProperty("products") - @ExcludeMissing - private val products: JsonField> = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val authenticationMethods: JsonField>, + private val beta: JsonField, + private val displayName: JsonField, + private val icon: JsonField, + private val logo: JsonField, + private val manual: JsonField, + private val mfaRequired: JsonField, + private val primaryColor: JsonField, + private val products: JsonField>, + private val additionalProperties: MutableMap, ) { - /** The id of the payroll provider used in Connect. */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("authentication_methods") + @ExcludeMissing + authenticationMethods: JsonField> = JsonMissing.of(), + @JsonProperty("beta") @ExcludeMissing beta: JsonField = JsonMissing.of(), + @JsonProperty("display_name") + @ExcludeMissing + displayName: JsonField = JsonMissing.of(), + @JsonProperty("icon") @ExcludeMissing icon: JsonField = JsonMissing.of(), + @JsonProperty("logo") @ExcludeMissing logo: JsonField = JsonMissing.of(), + @JsonProperty("manual") @ExcludeMissing manual: JsonField = JsonMissing.of(), + @JsonProperty("mfa_required") + @ExcludeMissing + mfaRequired: JsonField = JsonMissing.of(), + @JsonProperty("primary_color") + @ExcludeMissing + primaryColor: JsonField = JsonMissing.of(), + @JsonProperty("products") + @ExcludeMissing + products: JsonField> = JsonMissing.of(), + ) : this( + id, + authenticationMethods, + beta, + displayName, + icon, + logo, + manual, + mfaRequired, + primaryColor, + products, + mutableMapOf(), + ) + + /** + * The id of the payroll provider used in Connect. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") - /** The list of authentication methods supported by the provider. */ + /** + * The list of authentication methods supported by the provider. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun authenticationMethods(): Optional> = - Optional.ofNullable(authenticationMethods.getNullable("authentication_methods")) + authenticationMethods.getOptional("authentication_methods") - /** `true` if the integration is in a beta state, `false` otherwise */ - fun beta(): Optional = Optional.ofNullable(beta.getNullable("beta")) + /** + * `true` if the integration is in a beta state, `false` otherwise + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun beta(): Optional = beta.getOptional("beta") - /** The display name of the payroll provider. */ - fun displayName(): Optional = - Optional.ofNullable(displayName.getNullable("display_name")) + /** + * The display name of the payroll provider. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun displayName(): Optional = displayName.getOptional("display_name") - /** The url to the official icon of the payroll provider. */ - fun icon(): Optional = Optional.ofNullable(icon.getNullable("icon")) + /** + * The url to the official icon of the payroll provider. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun icon(): Optional = icon.getOptional("icon") - /** The url to the official logo of the payroll provider. */ - fun logo(): Optional = Optional.ofNullable(logo.getNullable("logo")) + /** + * The url to the official logo of the payroll provider. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun logo(): Optional = logo.getOptional("logo") /** * [DEPRECATED] Whether the Finch integration with this provider uses the Assisted Connect Flow * by default. This field is now deprecated. Please check for a `type` of `assisted` in the * `authentication_methods` field instead. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun manual(): Optional = Optional.ofNullable(manual.getNullable("manual")) + fun manual(): Optional = manual.getOptional("manual") - /** whether MFA is required for the provider. */ - fun mfaRequired(): Optional = - Optional.ofNullable(mfaRequired.getNullable("mfa_required")) + /** + * whether MFA is required for the provider. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mfaRequired(): Optional = mfaRequired.getOptional("mfa_required") - /** The hex code for the primary color of the payroll provider. */ - fun primaryColor(): Optional = - Optional.ofNullable(primaryColor.getNullable("primary_color")) + /** + * The hex code for the primary color of the payroll provider. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun primaryColor(): Optional = primaryColor.getOptional("primary_color") - /** The list of Finch products supported on this payroll provider. */ - fun products(): Optional> = Optional.ofNullable(products.getNullable("products")) + /** + * The list of Finch products supported on this payroll provider. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun products(): Optional> = products.getOptional("products") - /** The id of the payroll provider used in Connect. */ + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - /** The list of authentication methods supported by the provider. */ + /** + * Returns the raw JSON value of [authenticationMethods]. + * + * Unlike [authenticationMethods], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("authentication_methods") @ExcludeMissing fun _authenticationMethods(): JsonField> = authenticationMethods - /** `true` if the integration is in a beta state, `false` otherwise */ + /** + * Returns the raw JSON value of [beta]. + * + * Unlike [beta], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("beta") @ExcludeMissing fun _beta(): JsonField = beta - /** The display name of the payroll provider. */ + /** + * Returns the raw JSON value of [displayName]. + * + * Unlike [displayName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("display_name") @ExcludeMissing fun _displayName(): JsonField = displayName - /** The url to the official icon of the payroll provider. */ + /** + * Returns the raw JSON value of [icon]. + * + * Unlike [icon], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("icon") @ExcludeMissing fun _icon(): JsonField = icon - /** The url to the official logo of the payroll provider. */ + /** + * Returns the raw JSON value of [logo]. + * + * Unlike [logo], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("logo") @ExcludeMissing fun _logo(): JsonField = logo /** - * [DEPRECATED] Whether the Finch integration with this provider uses the Assisted Connect Flow - * by default. This field is now deprecated. Please check for a `type` of `assisted` in the - * `authentication_methods` field instead. + * Returns the raw JSON value of [manual]. + * + * Unlike [manual], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("manual") @ExcludeMissing fun _manual(): JsonField = manual - /** whether MFA is required for the provider. */ + /** + * Returns the raw JSON value of [mfaRequired]. + * + * Unlike [mfaRequired], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("mfa_required") @ExcludeMissing fun _mfaRequired(): JsonField = mfaRequired - /** The hex code for the primary color of the payroll provider. */ + /** + * Returns the raw JSON value of [primaryColor]. + * + * Unlike [primaryColor], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("primary_color") @ExcludeMissing fun _primaryColor(): JsonField = primaryColor - /** The list of Finch products supported on this payroll provider. */ + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("products") @ExcludeMissing fun _products(): JsonField> = products + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Provider = apply { - if (validated) { - return@apply - } - - id() - authenticationMethods().ifPresent { it.forEach { it.validate() } } - beta() - displayName() - icon() - logo() - manual() - mfaRequired() - primaryColor() - products() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Provider]. */ @JvmStatic fun builder() = Builder() } @@ -192,55 +284,85 @@ private constructor( /** The id of the payroll provider used in Connect. */ fun id(id: String) = id(JsonField.of(id)) - /** The id of the payroll provider used in Connect. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } /** The list of authentication methods supported by the provider. */ fun authenticationMethods(authenticationMethods: List) = authenticationMethods(JsonField.of(authenticationMethods)) - /** The list of authentication methods supported by the provider. */ + /** + * Sets [Builder.authenticationMethods] to an arbitrary JSON value. + * + * You should usually call [Builder.authenticationMethods] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun authenticationMethods(authenticationMethods: JsonField>) = apply { this.authenticationMethods = authenticationMethods.map { it.toMutableList() } } - /** The list of authentication methods supported by the provider. */ + /** + * Adds a single [AuthenticationMethod] to [authenticationMethods]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addAuthenticationMethod(authenticationMethod: AuthenticationMethod) = apply { authenticationMethods = - (authenticationMethods ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(authenticationMethod) + (authenticationMethods ?: JsonField.of(mutableListOf())).also { + checkKnown("authenticationMethods", it).add(authenticationMethod) } } /** `true` if the integration is in a beta state, `false` otherwise */ fun beta(beta: Boolean) = beta(JsonField.of(beta)) - /** `true` if the integration is in a beta state, `false` otherwise */ + /** + * Sets [Builder.beta] to an arbitrary JSON value. + * + * You should usually call [Builder.beta] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun beta(beta: JsonField) = apply { this.beta = beta } /** The display name of the payroll provider. */ fun displayName(displayName: String) = displayName(JsonField.of(displayName)) - /** The display name of the payroll provider. */ + /** + * Sets [Builder.displayName] to an arbitrary JSON value. + * + * You should usually call [Builder.displayName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun displayName(displayName: JsonField) = apply { this.displayName = displayName } /** The url to the official icon of the payroll provider. */ fun icon(icon: String) = icon(JsonField.of(icon)) - /** The url to the official icon of the payroll provider. */ + /** + * Sets [Builder.icon] to an arbitrary JSON value. + * + * You should usually call [Builder.icon] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun icon(icon: JsonField) = apply { this.icon = icon } /** The url to the official logo of the payroll provider. */ fun logo(logo: String) = logo(JsonField.of(logo)) - /** The url to the official logo of the payroll provider. */ + /** + * Sets [Builder.logo] to an arbitrary JSON value. + * + * You should usually call [Builder.logo] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun logo(logo: JsonField) = apply { this.logo = logo } /** @@ -251,22 +373,35 @@ private constructor( fun manual(manual: Boolean) = manual(JsonField.of(manual)) /** - * [DEPRECATED] Whether the Finch integration with this provider uses the Assisted Connect - * Flow by default. This field is now deprecated. Please check for a `type` of `assisted` in - * the `authentication_methods` field instead. + * Sets [Builder.manual] to an arbitrary JSON value. + * + * You should usually call [Builder.manual] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun manual(manual: JsonField) = apply { this.manual = manual } /** whether MFA is required for the provider. */ fun mfaRequired(mfaRequired: Boolean) = mfaRequired(JsonField.of(mfaRequired)) - /** whether MFA is required for the provider. */ + /** + * Sets [Builder.mfaRequired] to an arbitrary JSON value. + * + * You should usually call [Builder.mfaRequired] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun mfaRequired(mfaRequired: JsonField) = apply { this.mfaRequired = mfaRequired } /** The hex code for the primary color of the payroll provider. */ fun primaryColor(primaryColor: String) = primaryColor(JsonField.of(primaryColor)) - /** The hex code for the primary color of the payroll provider. */ + /** + * Sets [Builder.primaryColor] to an arbitrary JSON value. + * + * You should usually call [Builder.primaryColor] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun primaryColor(primaryColor: JsonField) = apply { this.primaryColor = primaryColor } @@ -274,22 +409,26 @@ private constructor( /** The list of Finch products supported on this payroll provider. */ fun products(products: List) = products(JsonField.of(products)) - /** The list of Finch products supported on this payroll provider. */ + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun products(products: JsonField>) = apply { this.products = products.map { it.toMutableList() } } - /** The list of Finch products supported on this payroll provider. */ + /** + * Adds a single [String] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addProduct(product: String) = apply { products = - (products ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(product) + (products ?: JsonField.of(mutableListOf())).also { + checkKnown("products", it).add(product) } } @@ -312,6 +451,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Provider]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Provider = Provider( id, @@ -324,76 +468,144 @@ private constructor( mfaRequired, primaryColor, (products ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Provider = apply { + if (validated) { + return@apply + } + + id() + authenticationMethods().ifPresent { it.forEach { it.validate() } } + beta() + displayName() + icon() + logo() + manual() + mfaRequired() + primaryColor() + products() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (authenticationMethods.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (beta.asKnown().isPresent) 1 else 0) + + (if (displayName.asKnown().isPresent) 1 else 0) + + (if (icon.asKnown().isPresent) 1 else 0) + + (if (logo.asKnown().isPresent) 1 else 0) + + (if (manual.asKnown().isPresent) 1 else 0) + + (if (mfaRequired.asKnown().isPresent) 1 else 0) + + (if (primaryColor.asKnown().isPresent) 1 else 0) + + (products.asKnown().getOrNull()?.size ?: 0) + class AuthenticationMethod - @JsonCreator private constructor( - @JsonProperty("benefits_support") - @ExcludeMissing - private val benefitsSupport: JsonField = JsonMissing.of(), - @JsonProperty("supported_fields") - @ExcludeMissing - private val supportedFields: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val benefitsSupport: JsonField, + private val supportedFields: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("benefits_support") + @ExcludeMissing + benefitsSupport: JsonField = JsonMissing.of(), + @JsonProperty("supported_fields") + @ExcludeMissing + supportedFields: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(benefitsSupport, supportedFields, type, mutableMapOf()) + /** * Each benefit type and their supported features. If the benefit type is not supported, the * property will be null + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ fun benefitsSupport(): Optional = - Optional.ofNullable(benefitsSupport.getNullable("benefits_support")) + benefitsSupport.getOptional("benefits_support") - /** The supported data fields returned by our HR and payroll endpoints */ + /** + * The supported data fields returned by our HR and payroll endpoints + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun supportedFields(): Optional = - Optional.ofNullable(supportedFields.getNullable("supported_fields")) + supportedFields.getOptional("supported_fields") - /** The type of authentication method. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The type of authentication method. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") /** - * Each benefit type and their supported features. If the benefit type is not supported, the - * property will be null + * Returns the raw JSON value of [benefitsSupport]. + * + * Unlike [benefitsSupport], this method doesn't throw if the JSON field has an unexpected + * type. */ @JsonProperty("benefits_support") @ExcludeMissing fun _benefitsSupport(): JsonField = benefitsSupport - /** The supported data fields returned by our HR and payroll endpoints */ + /** + * Returns the raw JSON value of [supportedFields]. + * + * Unlike [supportedFields], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("supported_fields") @ExcludeMissing fun _supportedFields(): JsonField = supportedFields - /** The type of authentication method. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): AuthenticationMethod = apply { - if (validated) { - return@apply - } - - benefitsSupport().ifPresent { it.validate() } - supportedFields().ifPresent { it.validate() } - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [AuthenticationMethod]. */ @JvmStatic fun builder() = Builder() } @@ -420,16 +632,16 @@ private constructor( fun benefitsSupport(benefitsSupport: BenefitsSupport?) = benefitsSupport(JsonField.ofNullable(benefitsSupport)) - /** - * Each benefit type and their supported features. If the benefit type is not supported, - * the property will be null - */ + /** Alias for calling [Builder.benefitsSupport] with `benefitsSupport.orElse(null)`. */ fun benefitsSupport(benefitsSupport: Optional) = - benefitsSupport(benefitsSupport.orElse(null)) + benefitsSupport(benefitsSupport.getOrNull()) /** - * Each benefit type and their supported features. If the benefit type is not supported, - * the property will be null + * Sets [Builder.benefitsSupport] to an arbitrary JSON value. + * + * You should usually call [Builder.benefitsSupport] with a well-typed [BenefitsSupport] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. */ fun benefitsSupport(benefitsSupport: JsonField) = apply { this.benefitsSupport = benefitsSupport @@ -439,11 +651,17 @@ private constructor( fun supportedFields(supportedFields: SupportedFields?) = supportedFields(JsonField.ofNullable(supportedFields)) - /** The supported data fields returned by our HR and payroll endpoints */ + /** Alias for calling [Builder.supportedFields] with `supportedFields.orElse(null)`. */ fun supportedFields(supportedFields: Optional) = - supportedFields(supportedFields.orElse(null)) + supportedFields(supportedFields.getOrNull()) - /** The supported data fields returned by our HR and payroll endpoints */ + /** + * Sets [Builder.supportedFields] to an arbitrary JSON value. + * + * You should usually call [Builder.supportedFields] with a well-typed [SupportedFields] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun supportedFields(supportedFields: JsonField) = apply { this.supportedFields = supportedFields } @@ -451,7 +669,13 @@ private constructor( /** The type of authentication method. */ fun type(type: Type) = type(JsonField.of(type)) - /** The type of authentication method. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -473,119 +697,228 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [AuthenticationMethod]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): AuthenticationMethod = AuthenticationMethod( benefitsSupport, supportedFields, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): AuthenticationMethod = apply { + if (validated) { + return@apply + } + + benefitsSupport().ifPresent { it.validate() } + supportedFields().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (benefitsSupport.asKnown().getOrNull()?.validity() ?: 0) + + (supportedFields.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + /** The supported data fields returned by our HR and payroll endpoints */ - @NoAutoDetect class SupportedFields - @JsonCreator private constructor( - @JsonProperty("company") - @ExcludeMissing - private val company: JsonField = JsonMissing.of(), - @JsonProperty("directory") - @ExcludeMissing - private val directory: JsonField = JsonMissing.of(), - @JsonProperty("employment") - @ExcludeMissing - private val employment: JsonField = JsonMissing.of(), - @JsonProperty("individual") - @ExcludeMissing - private val individual: JsonField = JsonMissing.of(), - @JsonProperty("pay_group") - @ExcludeMissing - private val payGroup: JsonField = JsonMissing.of(), - @JsonProperty("pay_statement") - @ExcludeMissing - private val payStatement: JsonField = JsonMissing.of(), - @JsonProperty("payment") - @ExcludeMissing - private val payment: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val company: JsonField, + private val directory: JsonField, + private val employment: JsonField, + private val individual: JsonField, + private val payGroup: JsonField, + private val payStatement: JsonField, + private val payment: JsonField, + private val additionalProperties: MutableMap, ) { - fun company(): Optional = - Optional.ofNullable(company.getNullable("company")) + @JsonCreator + private constructor( + @JsonProperty("company") + @ExcludeMissing + company: JsonField = JsonMissing.of(), + @JsonProperty("directory") + @ExcludeMissing + directory: JsonField = JsonMissing.of(), + @JsonProperty("employment") + @ExcludeMissing + employment: JsonField = JsonMissing.of(), + @JsonProperty("individual") + @ExcludeMissing + individual: JsonField = JsonMissing.of(), + @JsonProperty("pay_group") + @ExcludeMissing + payGroup: JsonField = JsonMissing.of(), + @JsonProperty("pay_statement") + @ExcludeMissing + payStatement: JsonField = JsonMissing.of(), + @JsonProperty("payment") + @ExcludeMissing + payment: JsonField = JsonMissing.of(), + ) : this( + company, + directory, + employment, + individual, + payGroup, + payStatement, + payment, + mutableMapOf(), + ) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun company(): Optional = company.getOptional("company") - fun directory(): Optional = - Optional.ofNullable(directory.getNullable("directory")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun directory(): Optional = directory.getOptional("directory") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun employment(): Optional = - Optional.ofNullable(employment.getNullable("employment")) + employment.getOptional("employment") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun individual(): Optional = - Optional.ofNullable(individual.getNullable("individual")) + individual.getOptional("individual") - fun payGroup(): Optional = - Optional.ofNullable(payGroup.getNullable("pay_group")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun payGroup(): Optional = payGroup.getOptional("pay_group") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ fun payStatement(): Optional = - Optional.ofNullable(payStatement.getNullable("pay_statement")) + payStatement.getOptional("pay_statement") - fun payment(): Optional = - Optional.ofNullable(payment.getNullable("payment")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun payment(): Optional = payment.getOptional("payment") + /** + * Returns the raw JSON value of [company]. + * + * Unlike [company], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("company") @ExcludeMissing fun _company(): JsonField = company + /** + * Returns the raw JSON value of [directory]. + * + * Unlike [directory], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("directory") @ExcludeMissing fun _directory(): JsonField = directory + /** + * Returns the raw JSON value of [employment]. + * + * Unlike [employment], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("employment") @ExcludeMissing fun _employment(): JsonField = employment + /** + * Returns the raw JSON value of [individual]. + * + * Unlike [individual], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("individual") @ExcludeMissing fun _individual(): JsonField = individual + /** + * Returns the raw JSON value of [payGroup]. + * + * Unlike [payGroup], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("pay_group") @ExcludeMissing fun _payGroup(): JsonField = payGroup + /** + * Returns the raw JSON value of [payStatement]. + * + * Unlike [payStatement], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("pay_statement") @ExcludeMissing fun _payStatement(): JsonField = payStatement + /** + * Returns the raw JSON value of [payment]. + * + * Unlike [payment], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("payment") @ExcludeMissing fun _payment(): JsonField = payment - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedFields = apply { - if (validated) { - return@apply - } - - company().ifPresent { it.validate() } - directory().ifPresent { it.validate() } - employment().ifPresent { it.validate() } - individual().ifPresent { it.validate() } - payGroup().ifPresent { it.validate() } - payStatement().ifPresent { it.validate() } - payment().ifPresent { it.validate() } - validated = true + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [SupportedFields]. */ @JvmStatic fun builder() = Builder() } @@ -615,6 +948,13 @@ private constructor( fun company(company: SupportedCompanyFields) = company(JsonField.of(company)) + /** + * Sets [Builder.company] to an arbitrary JSON value. + * + * You should usually call [Builder.company] with a well-typed + * [SupportedCompanyFields] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun company(company: JsonField) = apply { this.company = company } @@ -622,6 +962,13 @@ private constructor( fun directory(directory: SupportedDirectoryFields) = directory(JsonField.of(directory)) + /** + * Sets [Builder.directory] to an arbitrary JSON value. + * + * You should usually call [Builder.directory] with a well-typed + * [SupportedDirectoryFields] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ fun directory(directory: JsonField) = apply { this.directory = directory } @@ -629,6 +976,13 @@ private constructor( fun employment(employment: SupportedEmploymentFields) = employment(JsonField.of(employment)) + /** + * Sets [Builder.employment] to an arbitrary JSON value. + * + * You should usually call [Builder.employment] with a well-typed + * [SupportedEmploymentFields] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ fun employment(employment: JsonField) = apply { this.employment = employment } @@ -636,12 +990,26 @@ private constructor( fun individual(individual: SupportedIndividualFields) = individual(JsonField.of(individual)) + /** + * Sets [Builder.individual] to an arbitrary JSON value. + * + * You should usually call [Builder.individual] with a well-typed + * [SupportedIndividualFields] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ fun individual(individual: JsonField) = apply { this.individual = individual } fun payGroup(payGroup: SupportedPayGroupFields) = payGroup(JsonField.of(payGroup)) + /** + * Sets [Builder.payGroup] to an arbitrary JSON value. + * + * You should usually call [Builder.payGroup] with a well-typed + * [SupportedPayGroupFields] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun payGroup(payGroup: JsonField) = apply { this.payGroup = payGroup } @@ -649,12 +1017,26 @@ private constructor( fun payStatement(payStatement: SupportedPayStatementFields) = payStatement(JsonField.of(payStatement)) + /** + * Sets [Builder.payStatement] to an arbitrary JSON value. + * + * You should usually call [Builder.payStatement] with a well-typed + * [SupportedPayStatementFields] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ fun payStatement(payStatement: JsonField) = apply { this.payStatement = payStatement } fun payment(payment: SupportedPaymentFields) = payment(JsonField.of(payment)) + /** + * Sets [Builder.payment] to an arbitrary JSON value. + * + * You should usually call [Builder.payment] with a well-typed + * [SupportedPaymentFields] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun payment(payment: JsonField) = apply { this.payment = payment } @@ -681,6 +1063,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedFields = SupportedFields( company, @@ -690,126 +1077,258 @@ private constructor( payGroup, payStatement, payment, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect - class SupportedCompanyFields - @JsonCreator - private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("accounts") - @ExcludeMissing - private val accounts: JsonField = JsonMissing.of(), - @JsonProperty("departments") - @ExcludeMissing - private val departments: JsonField = JsonMissing.of(), - @JsonProperty("ein") - @ExcludeMissing - private val ein: JsonField = JsonMissing.of(), - @JsonProperty("entity") - @ExcludeMissing - private val entity: JsonField = JsonMissing.of(), - @JsonProperty("legal_name") - @ExcludeMissing - private val legalName: JsonField = JsonMissing.of(), - @JsonProperty("locations") - @ExcludeMissing - private val locations: JsonField = JsonMissing.of(), - @JsonProperty("primary_email") - @ExcludeMissing - private val primaryEmail: JsonField = JsonMissing.of(), - @JsonProperty("primary_phone_number") - @ExcludeMissing - private val primaryPhoneNumber: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun accounts(): Optional = - Optional.ofNullable(accounts.getNullable("accounts")) + private var validated: Boolean = false - fun departments(): Optional = - Optional.ofNullable(departments.getNullable("departments")) + fun validate(): SupportedFields = apply { + if (validated) { + return@apply + } - fun ein(): Optional = Optional.ofNullable(ein.getNullable("ein")) + company().ifPresent { it.validate() } + directory().ifPresent { it.validate() } + employment().ifPresent { it.validate() } + individual().ifPresent { it.validate() } + payGroup().ifPresent { it.validate() } + payStatement().ifPresent { it.validate() } + payment().ifPresent { it.validate() } + validated = true + } - fun entity(): Optional = Optional.ofNullable(entity.getNullable("entity")) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } - fun legalName(): Optional = - Optional.ofNullable(legalName.getNullable("legal_name")) + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (company.asKnown().getOrNull()?.validity() ?: 0) + + (directory.asKnown().getOrNull()?.validity() ?: 0) + + (employment.asKnown().getOrNull()?.validity() ?: 0) + + (individual.asKnown().getOrNull()?.validity() ?: 0) + + (payGroup.asKnown().getOrNull()?.validity() ?: 0) + + (payStatement.asKnown().getOrNull()?.validity() ?: 0) + + (payment.asKnown().getOrNull()?.validity() ?: 0) - fun locations(): Optional = - Optional.ofNullable(locations.getNullable("locations")) + class SupportedCompanyFields + private constructor( + private val id: JsonField, + private val accounts: JsonField, + private val departments: JsonField, + private val ein: JsonField, + private val entity: JsonField, + private val legalName: JsonField, + private val locations: JsonField, + private val primaryEmail: JsonField, + private val primaryPhoneNumber: JsonField, + private val additionalProperties: MutableMap, + ) { - fun primaryEmail(): Optional = - Optional.ofNullable(primaryEmail.getNullable("primary_email")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("accounts") + @ExcludeMissing + accounts: JsonField = JsonMissing.of(), + @JsonProperty("departments") + @ExcludeMissing + departments: JsonField = JsonMissing.of(), + @JsonProperty("ein") @ExcludeMissing ein: JsonField = JsonMissing.of(), + @JsonProperty("entity") + @ExcludeMissing + entity: JsonField = JsonMissing.of(), + @JsonProperty("legal_name") + @ExcludeMissing + legalName: JsonField = JsonMissing.of(), + @JsonProperty("locations") + @ExcludeMissing + locations: JsonField = JsonMissing.of(), + @JsonProperty("primary_email") + @ExcludeMissing + primaryEmail: JsonField = JsonMissing.of(), + @JsonProperty("primary_phone_number") + @ExcludeMissing + primaryPhoneNumber: JsonField = JsonMissing.of(), + ) : this( + id, + accounts, + departments, + ein, + entity, + legalName, + locations, + primaryEmail, + primaryPhoneNumber, + mutableMapOf(), + ) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun accounts(): Optional = accounts.getOptional("accounts") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun departments(): Optional = departments.getOptional("departments") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun ein(): Optional = ein.getOptional("ein") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun entity(): Optional = entity.getOptional("entity") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun legalName(): Optional = legalName.getOptional("legal_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun locations(): Optional = locations.getOptional("locations") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun primaryEmail(): Optional = primaryEmail.getOptional("primary_email") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ fun primaryPhoneNumber(): Optional = - Optional.ofNullable(primaryPhoneNumber.getNullable("primary_phone_number")) + primaryPhoneNumber.getOptional("primary_phone_number") + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [accounts]. + * + * Unlike [accounts], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("accounts") @ExcludeMissing fun _accounts(): JsonField = accounts + /** + * Returns the raw JSON value of [departments]. + * + * Unlike [departments], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("departments") @ExcludeMissing fun _departments(): JsonField = departments + /** + * Returns the raw JSON value of [ein]. + * + * Unlike [ein], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("ein") @ExcludeMissing fun _ein(): JsonField = ein + /** + * Returns the raw JSON value of [entity]. + * + * Unlike [entity], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("entity") @ExcludeMissing fun _entity(): JsonField = entity + /** + * Returns the raw JSON value of [legalName]. + * + * Unlike [legalName], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("legal_name") @ExcludeMissing fun _legalName(): JsonField = legalName + /** + * Returns the raw JSON value of [locations]. + * + * Unlike [locations], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("locations") @ExcludeMissing fun _locations(): JsonField = locations + /** + * Returns the raw JSON value of [primaryEmail]. + * + * Unlike [primaryEmail], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("primary_email") @ExcludeMissing fun _primaryEmail(): JsonField = primaryEmail + /** + * Returns the raw JSON value of [primaryPhoneNumber]. + * + * Unlike [primaryPhoneNumber], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("primary_phone_number") @ExcludeMissing fun _primaryPhoneNumber(): JsonField = primaryPhoneNumber + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedCompanyFields = apply { - if (validated) { - return@apply - } - - id() - accounts().ifPresent { it.validate() } - departments().ifPresent { it.validate() } - ein() - entity().ifPresent { it.validate() } - legalName() - locations().ifPresent { it.validate() } - primaryEmail() - primaryPhoneNumber() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedCompanyFields]. + */ @JvmStatic fun builder() = Builder() } @@ -844,35 +1363,84 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun accounts(accounts: Accounts) = accounts(JsonField.of(accounts)) + /** + * Sets [Builder.accounts] to an arbitrary JSON value. + * + * You should usually call [Builder.accounts] with a well-typed [Accounts] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun accounts(accounts: JsonField) = apply { this.accounts = accounts } fun departments(departments: Departments) = departments(JsonField.of(departments)) + /** + * Sets [Builder.departments] to an arbitrary JSON value. + * + * You should usually call [Builder.departments] with a well-typed [Departments] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun departments(departments: JsonField) = apply { this.departments = departments } fun ein(ein: Boolean) = ein(JsonField.of(ein)) + /** + * Sets [Builder.ein] to an arbitrary JSON value. + * + * You should usually call [Builder.ein] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun ein(ein: JsonField) = apply { this.ein = ein } fun entity(entity: Entity) = entity(JsonField.of(entity)) + /** + * Sets [Builder.entity] to an arbitrary JSON value. + * + * You should usually call [Builder.entity] with a well-typed [Entity] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun entity(entity: JsonField) = apply { this.entity = entity } fun legalName(legalName: Boolean) = legalName(JsonField.of(legalName)) + /** + * Sets [Builder.legalName] to an arbitrary JSON value. + * + * You should usually call [Builder.legalName] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun legalName(legalName: JsonField) = apply { this.legalName = legalName } fun locations(locations: Locations) = locations(JsonField.of(locations)) + /** + * Sets [Builder.locations] to an arbitrary JSON value. + * + * You should usually call [Builder.locations] with a well-typed [Locations] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun locations(locations: JsonField) = apply { this.locations = locations } @@ -880,6 +1448,13 @@ private constructor( fun primaryEmail(primaryEmail: Boolean) = primaryEmail(JsonField.of(primaryEmail)) + /** + * Sets [Builder.primaryEmail] to an arbitrary JSON value. + * + * You should usually call [Builder.primaryEmail] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun primaryEmail(primaryEmail: JsonField) = apply { this.primaryEmail = primaryEmail } @@ -887,6 +1462,13 @@ private constructor( fun primaryPhoneNumber(primaryPhoneNumber: Boolean) = primaryPhoneNumber(JsonField.of(primaryPhoneNumber)) + /** + * Sets [Builder.primaryPhoneNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.primaryPhoneNumber] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun primaryPhoneNumber(primaryPhoneNumber: JsonField) = apply { this.primaryPhoneNumber = primaryPhoneNumber } @@ -913,6 +1495,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedCompanyFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedCompanyFields = SupportedCompanyFields( id, @@ -924,91 +1511,189 @@ private constructor( locations, primaryEmail, primaryPhoneNumber, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): SupportedCompanyFields = apply { + if (validated) { + return@apply + } + + id() + accounts().ifPresent { it.validate() } + departments().ifPresent { it.validate() } + ein() + entity().ifPresent { it.validate() } + legalName() + locations().ifPresent { it.validate() } + primaryEmail() + primaryPhoneNumber() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (accounts.asKnown().getOrNull()?.validity() ?: 0) + + (departments.asKnown().getOrNull()?.validity() ?: 0) + + (if (ein.asKnown().isPresent) 1 else 0) + + (entity.asKnown().getOrNull()?.validity() ?: 0) + + (if (legalName.asKnown().isPresent) 1 else 0) + + (locations.asKnown().getOrNull()?.validity() ?: 0) + + (if (primaryEmail.asKnown().isPresent) 1 else 0) + + (if (primaryPhoneNumber.asKnown().isPresent) 1 else 0) + class Accounts - @JsonCreator private constructor( - @JsonProperty("account_name") - @ExcludeMissing - private val accountName: JsonField = JsonMissing.of(), - @JsonProperty("account_number") - @ExcludeMissing - private val accountNumber: JsonField = JsonMissing.of(), - @JsonProperty("account_type") - @ExcludeMissing - private val accountType: JsonField = JsonMissing.of(), - @JsonProperty("institution_name") - @ExcludeMissing - private val institutionName: JsonField = JsonMissing.of(), - @JsonProperty("routing_number") - @ExcludeMissing - private val routingNumber: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val accountName: JsonField, + private val accountNumber: JsonField, + private val accountType: JsonField, + private val institutionName: JsonField, + private val routingNumber: JsonField, + private val additionalProperties: MutableMap, ) { - fun accountName(): Optional = - Optional.ofNullable(accountName.getNullable("account_name")) - - fun accountNumber(): Optional = - Optional.ofNullable(accountNumber.getNullable("account_number")) + @JsonCreator + private constructor( + @JsonProperty("account_name") + @ExcludeMissing + accountName: JsonField = JsonMissing.of(), + @JsonProperty("account_number") + @ExcludeMissing + accountNumber: JsonField = JsonMissing.of(), + @JsonProperty("account_type") + @ExcludeMissing + accountType: JsonField = JsonMissing.of(), + @JsonProperty("institution_name") + @ExcludeMissing + institutionName: JsonField = JsonMissing.of(), + @JsonProperty("routing_number") + @ExcludeMissing + routingNumber: JsonField = JsonMissing.of(), + ) : this( + accountName, + accountNumber, + accountType, + institutionName, + routingNumber, + mutableMapOf(), + ) - fun accountType(): Optional = - Optional.ofNullable(accountType.getNullable("account_type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun accountName(): Optional = accountName.getOptional("account_name") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun accountNumber(): Optional = + accountNumber.getOptional("account_number") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun accountType(): Optional = accountType.getOptional("account_type") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun institutionName(): Optional = - Optional.ofNullable(institutionName.getNullable("institution_name")) + institutionName.getOptional("institution_name") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun routingNumber(): Optional = - Optional.ofNullable(routingNumber.getNullable("routing_number")) - + routingNumber.getOptional("routing_number") + + /** + * Returns the raw JSON value of [accountName]. + * + * Unlike [accountName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("account_name") @ExcludeMissing fun _accountName(): JsonField = accountName + /** + * Returns the raw JSON value of [accountNumber]. + * + * Unlike [accountNumber], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("account_number") @ExcludeMissing fun _accountNumber(): JsonField = accountNumber + /** + * Returns the raw JSON value of [accountType]. + * + * Unlike [accountType], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("account_type") @ExcludeMissing fun _accountType(): JsonField = accountType + /** + * Returns the raw JSON value of [institutionName]. + * + * Unlike [institutionName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("institution_name") @ExcludeMissing fun _institutionName(): JsonField = institutionName + /** + * Returns the raw JSON value of [routingNumber]. + * + * Unlike [routingNumber], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("routing_number") @ExcludeMissing fun _routingNumber(): JsonField = routingNumber + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Accounts = apply { - if (validated) { - return@apply - } - - accountName() - accountNumber() - accountType() - institutionName() - routingNumber() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Accounts]. */ @JvmStatic fun builder() = Builder() } @@ -1036,6 +1721,13 @@ private constructor( fun accountName(accountName: Boolean) = accountName(JsonField.of(accountName)) + /** + * Sets [Builder.accountName] to an arbitrary JSON value. + * + * You should usually call [Builder.accountName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun accountName(accountName: JsonField) = apply { this.accountName = accountName } @@ -1043,6 +1735,13 @@ private constructor( fun accountNumber(accountNumber: Boolean) = accountNumber(JsonField.of(accountNumber)) + /** + * Sets [Builder.accountNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.accountNumber] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun accountNumber(accountNumber: JsonField) = apply { this.accountNumber = accountNumber } @@ -1050,6 +1749,13 @@ private constructor( fun accountType(accountType: Boolean) = accountType(JsonField.of(accountType)) + /** + * Sets [Builder.accountType] to an arbitrary JSON value. + * + * You should usually call [Builder.accountType] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun accountType(accountType: JsonField) = apply { this.accountType = accountType } @@ -1057,6 +1763,13 @@ private constructor( fun institutionName(institutionName: Boolean) = institutionName(JsonField.of(institutionName)) + /** + * Sets [Builder.institutionName] to an arbitrary JSON value. + * + * You should usually call [Builder.institutionName] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun institutionName(institutionName: JsonField) = apply { this.institutionName = institutionName } @@ -1064,6 +1777,13 @@ private constructor( fun routingNumber(routingNumber: Boolean) = routingNumber(JsonField.of(routingNumber)) + /** + * Sets [Builder.routingNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.routingNumber] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun routingNumber(routingNumber: JsonField) = apply { this.routingNumber = routingNumber } @@ -1090,6 +1810,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Accounts]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Accounts = Accounts( accountName, @@ -1097,10 +1822,47 @@ private constructor( accountType, institutionName, routingNumber, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Accounts = apply { + if (validated) { + return@apply + } + + accountName() + accountNumber() + accountType() + institutionName() + routingNumber() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountName.asKnown().isPresent) 1 else 0) + + (if (accountNumber.asKnown().isPresent) 1 else 0) + + (if (accountType.asKnown().isPresent) 1 else 0) + + (if (institutionName.asKnown().isPresent) 1 else 0) + + (if (routingNumber.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1119,51 +1881,70 @@ private constructor( "Accounts{accountName=$accountName, accountNumber=$accountNumber, accountType=$accountType, institutionName=$institutionName, routingNumber=$routingNumber, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Departments - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("parent") - @ExcludeMissing - private val parent: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val parent: JsonField, + private val additionalProperties: MutableMap, ) { - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - fun parent(): Optional = - Optional.ofNullable(parent.getNullable("parent")) - + @JsonCreator + private constructor( + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("parent") + @ExcludeMissing + parent: JsonField = JsonMissing.of(), + ) : this(name, parent, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun parent(): Optional = parent.getOptional("parent") + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + /** + * Returns the raw JSON value of [parent]. + * + * Unlike [parent], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("parent") @ExcludeMissing fun _parent(): JsonField = parent + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Departments = apply { - if (validated) { - return@apply - } - - name() - parent().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Departments]. + */ @JvmStatic fun builder() = Builder() } @@ -1184,10 +1965,24 @@ private constructor( fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun parent(parent: Parent) = parent(JsonField.of(parent)) + /** + * Sets [Builder.parent] to an arbitrary JSON value. + * + * You should usually call [Builder.parent] with a well-typed [Parent] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun parent(parent: JsonField) = apply { this.parent = parent } fun additionalProperties(additionalProperties: Map) = @@ -1212,46 +2007,90 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Departments]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Departments = - Departments(name, parent, additionalProperties.toImmutable()) + Departments(name, parent, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Departments = apply { + if (validated) { + return@apply + } + + name() + parent().ifPresent { it.validate() } + validated = true } - @NoAutoDetect + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (parent.asKnown().getOrNull()?.validity() ?: 0) + class Parent - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - fun name(): Optional = - Optional.ofNullable(name.getNullable("name")) - + @JsonCreator + private constructor( + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Parent = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Parent]. + */ @JvmStatic fun builder() = Builder() } @@ -1270,6 +2109,13 @@ private constructor( fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = @@ -1294,9 +2140,43 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Parent = Parent(name, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Parent]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): Parent = Parent(name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Parent = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1333,51 +2213,68 @@ private constructor( "Departments{name=$name, parent=$parent, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Entity - @JsonCreator private constructor( - @JsonProperty("subtype") - @ExcludeMissing - private val subtype: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val subtype: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun subtype(): Optional = - Optional.ofNullable(subtype.getNullable("subtype")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - + @JsonCreator + private constructor( + @JsonProperty("subtype") + @ExcludeMissing + subtype: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(subtype, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun subtype(): Optional = subtype.getOptional("subtype") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [subtype]. + * + * Unlike [subtype], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Entity = apply { - if (validated) { - return@apply - } - - subtype() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Entity]. */ @JvmStatic fun builder() = Builder() } @@ -1398,10 +2295,24 @@ private constructor( fun subtype(subtype: Boolean) = subtype(JsonField.of(subtype)) + /** + * Sets [Builder.subtype] to an arbitrary JSON value. + * + * You should usually call [Builder.subtype] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun subtype(subtype: JsonField) = apply { this.subtype = subtype } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = @@ -1426,10 +2337,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Entity]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Entity = - Entity(subtype, type, additionalProperties.toImmutable()) + Entity(subtype, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Entity = apply { + if (validated) { + return@apply + } + + subtype() + type() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (subtype.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1448,86 +2395,144 @@ private constructor( "Entity{subtype=$subtype, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Locations - @JsonCreator private constructor( - @JsonProperty("city") - @ExcludeMissing - private val city: JsonField = JsonMissing.of(), - @JsonProperty("country") - @ExcludeMissing - private val country: JsonField = JsonMissing.of(), - @JsonProperty("line1") - @ExcludeMissing - private val line1: JsonField = JsonMissing.of(), - @JsonProperty("line2") - @ExcludeMissing - private val line2: JsonField = JsonMissing.of(), - @JsonProperty("postal_code") - @ExcludeMissing - private val postalCode: JsonField = JsonMissing.of(), - @JsonProperty("state") - @ExcludeMissing - private val state: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val city: JsonField, + private val country: JsonField, + private val line1: JsonField, + private val line2: JsonField, + private val postalCode: JsonField, + private val state: JsonField, + private val additionalProperties: MutableMap, ) { - fun city(): Optional = Optional.ofNullable(city.getNullable("city")) - - fun country(): Optional = - Optional.ofNullable(country.getNullable("country")) - - fun line1(): Optional = Optional.ofNullable(line1.getNullable("line1")) - - fun line2(): Optional = Optional.ofNullable(line2.getNullable("line2")) - - fun postalCode(): Optional = - Optional.ofNullable(postalCode.getNullable("postal_code")) - - fun state(): Optional = Optional.ofNullable(state.getNullable("state")) - + @JsonCreator + private constructor( + @JsonProperty("city") + @ExcludeMissing + city: JsonField = JsonMissing.of(), + @JsonProperty("country") + @ExcludeMissing + country: JsonField = JsonMissing.of(), + @JsonProperty("line1") + @ExcludeMissing + line1: JsonField = JsonMissing.of(), + @JsonProperty("line2") + @ExcludeMissing + line2: JsonField = JsonMissing.of(), + @JsonProperty("postal_code") + @ExcludeMissing + postalCode: JsonField = JsonMissing.of(), + @JsonProperty("state") + @ExcludeMissing + state: JsonField = JsonMissing.of(), + ) : this(city, country, line1, line2, postalCode, state, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun city(): Optional = city.getOptional("city") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun country(): Optional = country.getOptional("country") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun line1(): Optional = line1.getOptional("line1") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun line2(): Optional = line2.getOptional("line2") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun postalCode(): Optional = postalCode.getOptional("postal_code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun state(): Optional = state.getOptional("state") + + /** + * Returns the raw JSON value of [city]. + * + * Unlike [city], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("city") @ExcludeMissing fun _city(): JsonField = city + /** + * Returns the raw JSON value of [country]. + * + * Unlike [country], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("country") @ExcludeMissing fun _country(): JsonField = country + /** + * Returns the raw JSON value of [line1]. + * + * Unlike [line1], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("line1") @ExcludeMissing fun _line1(): JsonField = line1 + /** + * Returns the raw JSON value of [line2]. + * + * Unlike [line2], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("line2") @ExcludeMissing fun _line2(): JsonField = line2 + /** + * Returns the raw JSON value of [postalCode]. + * + * Unlike [postalCode], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("postal_code") @ExcludeMissing fun _postalCode(): JsonField = postalCode + /** + * Returns the raw JSON value of [state]. + * + * Unlike [state], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("state") @ExcludeMissing fun _state(): JsonField = state + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Locations = apply { - if (validated) { - return@apply - } - - city() - country() - line1() - line2() - postalCode() - state() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Locations]. + */ @JvmStatic fun builder() = Builder() } @@ -1556,28 +2561,70 @@ private constructor( fun city(city: Boolean) = city(JsonField.of(city)) + /** + * Sets [Builder.city] to an arbitrary JSON value. + * + * You should usually call [Builder.city] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun city(city: JsonField) = apply { this.city = city } fun country(country: Boolean) = country(JsonField.of(country)) + /** + * Sets [Builder.country] to an arbitrary JSON value. + * + * You should usually call [Builder.country] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun country(country: JsonField) = apply { this.country = country } fun line1(line1: Boolean) = line1(JsonField.of(line1)) + /** + * Sets [Builder.line1] to an arbitrary JSON value. + * + * You should usually call [Builder.line1] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun line1(line1: JsonField) = apply { this.line1 = line1 } fun line2(line2: Boolean) = line2(JsonField.of(line2)) + /** + * Sets [Builder.line2] to an arbitrary JSON value. + * + * You should usually call [Builder.line2] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun line2(line2: JsonField) = apply { this.line2 = line2 } fun postalCode(postalCode: Boolean) = postalCode(JsonField.of(postalCode)) + /** + * Sets [Builder.postalCode] to an arbitrary JSON value. + * + * You should usually call [Builder.postalCode] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun postalCode(postalCode: JsonField) = apply { this.postalCode = postalCode } fun state(state: Boolean) = state(JsonField.of(state)) + /** + * Sets [Builder.state] to an arbitrary JSON value. + * + * You should usually call [Builder.state] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun state(state: JsonField) = apply { this.state = state } fun additionalProperties(additionalProperties: Map) = @@ -1602,6 +2649,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Locations]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Locations = Locations( city, @@ -1610,10 +2662,49 @@ private constructor( line2, postalCode, state, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Locations = apply { + if (validated) { + return@apply + } + + city() + country() + line1() + line2() + postalCode() + state() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (city.asKnown().isPresent) 1 else 0) + + (if (country.asKnown().isPresent) 1 else 0) + + (if (line1.asKnown().isPresent) 1 else 0) + + (if (line2.asKnown().isPresent) 1 else 0) + + (if (postalCode.asKnown().isPresent) 1 else 0) + + (if (state.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1650,51 +2741,71 @@ private constructor( "SupportedCompanyFields{id=$id, accounts=$accounts, departments=$departments, ein=$ein, entity=$entity, legalName=$legalName, locations=$locations, primaryEmail=$primaryEmail, primaryPhoneNumber=$primaryPhoneNumber, additionalProperties=$additionalProperties}" } - @NoAutoDetect class SupportedDirectoryFields - @JsonCreator private constructor( - @JsonProperty("individuals") - @ExcludeMissing - private val individuals: JsonField = JsonMissing.of(), - @JsonProperty("paging") - @ExcludeMissing - private val paging: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val individuals: JsonField, + private val paging: JsonField, + private val additionalProperties: MutableMap, ) { - fun individuals(): Optional = - Optional.ofNullable(individuals.getNullable("individuals")) - - fun paging(): Optional = Optional.ofNullable(paging.getNullable("paging")) - + @JsonCreator + private constructor( + @JsonProperty("individuals") + @ExcludeMissing + individuals: JsonField = JsonMissing.of(), + @JsonProperty("paging") + @ExcludeMissing + paging: JsonField = JsonMissing.of(), + ) : this(individuals, paging, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun individuals(): Optional = individuals.getOptional("individuals") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun paging(): Optional = paging.getOptional("paging") + + /** + * Returns the raw JSON value of [individuals]. + * + * Unlike [individuals], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("individuals") @ExcludeMissing fun _individuals(): JsonField = individuals + /** + * Returns the raw JSON value of [paging]. + * + * Unlike [paging], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("paging") @ExcludeMissing fun _paging(): JsonField = paging + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedDirectoryFields = apply { - if (validated) { - return@apply - } - - individuals().ifPresent { it.validate() } - paging().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedDirectoryFields]. + */ @JvmStatic fun builder() = Builder() } @@ -1716,12 +2827,26 @@ private constructor( fun individuals(individuals: Individuals) = individuals(JsonField.of(individuals)) + /** + * Sets [Builder.individuals] to an arbitrary JSON value. + * + * You should usually call [Builder.individuals] with a well-typed [Individuals] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun individuals(individuals: JsonField) = apply { this.individuals = individuals } fun paging(paging: Paging) = paging(JsonField.of(paging)) + /** + * Sets [Builder.paging] to an arbitrary JSON value. + * + * You should usually call [Builder.paging] with a well-typed [Paging] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun paging(paging: JsonField) = apply { this.paging = paging } fun additionalProperties(additionalProperties: Map) = apply { @@ -1746,114 +2871,223 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedDirectoryFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedDirectoryFields = SupportedDirectoryFields( individuals, paging, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect - class Individuals - @JsonCreator - private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("department") - @ExcludeMissing - private val department: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("is_active") - @ExcludeMissing - private val isActive: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), - @JsonProperty("manager") - @ExcludeMissing - private val manager: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + private var validated: Boolean = false - fun department(): Optional = - Optional.ofNullable(department.getNullable("department")) + fun validate(): SupportedDirectoryFields = apply { + if (validated) { + return@apply + } - fun firstName(): Optional = - Optional.ofNullable(firstName.getNullable("first_name")) + individuals().ifPresent { it.validate() } + paging().ifPresent { it.validate() } + validated = true + } - fun isActive(): Optional = - Optional.ofNullable(isActive.getNullable("is_active")) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } - fun lastName(): Optional = - Optional.ofNullable(lastName.getNullable("last_name")) + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (individuals.asKnown().getOrNull()?.validity() ?: 0) + + (paging.asKnown().getOrNull()?.validity() ?: 0) - fun manager(): Optional = - Optional.ofNullable(manager.getNullable("manager")) + class Individuals + private constructor( + private val id: JsonField, + private val department: JsonField, + private val firstName: JsonField, + private val isActive: JsonField, + private val lastName: JsonField, + private val manager: JsonField, + private val middleName: JsonField, + private val additionalProperties: MutableMap, + ) { - fun middleName(): Optional = - Optional.ofNullable(middleName.getNullable("middle_name")) + @JsonCreator + private constructor( + @JsonProperty("id") + @ExcludeMissing + id: JsonField = JsonMissing.of(), + @JsonProperty("department") + @ExcludeMissing + department: JsonField = JsonMissing.of(), + @JsonProperty("first_name") + @ExcludeMissing + firstName: JsonField = JsonMissing.of(), + @JsonProperty("is_active") + @ExcludeMissing + isActive: JsonField = JsonMissing.of(), + @JsonProperty("last_name") + @ExcludeMissing + lastName: JsonField = JsonMissing.of(), + @JsonProperty("manager") + @ExcludeMissing + manager: JsonField = JsonMissing.of(), + @JsonProperty("middle_name") + @ExcludeMissing + middleName: JsonField = JsonMissing.of(), + ) : this( + id, + department, + firstName, + isActive, + lastName, + manager, + middleName, + mutableMapOf(), + ) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun department(): Optional = department.getOptional("department") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun isActive(): Optional = isActive.getOptional("is_active") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun manager(): Optional = manager.getOptional("manager") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [department]. + * + * Unlike [department], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("department") @ExcludeMissing fun _department(): JsonField = department + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName + /** + * Returns the raw JSON value of [isActive]. + * + * Unlike [isActive], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("is_active") @ExcludeMissing fun _isActive(): JsonField = isActive + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName + /** + * Returns the raw JSON value of [manager]. + * + * Unlike [manager], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("manager") @ExcludeMissing fun _manager(): JsonField = manager + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("middle_name") @ExcludeMissing fun _middleName(): JsonField = middleName + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Individuals = apply { - if (validated) { - return@apply - } - - id() - department() - firstName() - isActive() - lastName() - manager().ifPresent { it.validate() } - middleName() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Individuals]. + */ @JvmStatic fun builder() = Builder() } @@ -1884,38 +3118,87 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun department(department: Boolean) = department(JsonField.of(department)) + /** + * Sets [Builder.department] to an arbitrary JSON value. + * + * You should usually call [Builder.department] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun department(department: JsonField) = apply { this.department = department } fun firstName(firstName: Boolean) = firstName(JsonField.of(firstName)) + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun firstName(firstName: JsonField) = apply { this.firstName = firstName } fun isActive(isActive: Boolean) = isActive(JsonField.of(isActive)) + /** + * Sets [Builder.isActive] to an arbitrary JSON value. + * + * You should usually call [Builder.isActive] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun isActive(isActive: JsonField) = apply { this.isActive = isActive } fun lastName(lastName: Boolean) = lastName(JsonField.of(lastName)) + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun lastName(lastName: JsonField) = apply { this.lastName = lastName } fun manager(manager: Manager) = manager(JsonField.of(manager)) + /** + * Sets [Builder.manager] to an arbitrary JSON value. + * + * You should usually call [Builder.manager] with a well-typed [Manager] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun manager(manager: JsonField) = apply { this.manager = manager } fun middleName(middleName: Boolean) = middleName(JsonField.of(middleName)) + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun middleName(middleName: JsonField) = apply { this.middleName = middleName } @@ -1942,6 +3225,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Individuals]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Individuals = Individuals( id, @@ -1951,45 +3239,95 @@ private constructor( lastName, manager, middleName, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Individuals = apply { + if (validated) { + return@apply + } + + id() + department() + firstName() + isActive() + lastName() + manager().ifPresent { it.validate() } + middleName() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (department.asKnown().isPresent) 1 else 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (if (isActive.asKnown().isPresent) 1 else 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (manager.asKnown().getOrNull()?.validity() ?: 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + class Manager - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val id: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - + @JsonCreator + private constructor( + @JsonProperty("id") + @ExcludeMissing + id: JsonField = JsonMissing.of() + ) : this(id, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Manager = apply { - if (validated) { - return@apply - } - - id() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Manager]. + */ @JvmStatic fun builder() = Builder() } @@ -2008,6 +3346,13 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun additionalProperties(additionalProperties: Map) = @@ -2032,9 +3377,43 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Manager = Manager(id, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Manager]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ + fun build(): Manager = Manager(id, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Manager = apply { + if (validated) { + return@apply + } + + id() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (id.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2071,51 +3450,68 @@ private constructor( "Individuals{id=$id, department=$department, firstName=$firstName, isActive=$isActive, lastName=$lastName, manager=$manager, middleName=$middleName, additionalProperties=$additionalProperties}" } - @NoAutoDetect - class Paging - @JsonCreator - private constructor( - @JsonProperty("count") - @ExcludeMissing - private val count: JsonField = JsonMissing.of(), - @JsonProperty("offset") - @ExcludeMissing - private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun count(): Optional = Optional.ofNullable(count.getNullable("count")) - - fun offset(): Optional = - Optional.ofNullable(offset.getNullable("offset")) + class Paging + private constructor( + private val count: JsonField, + private val offset: JsonField, + private val additionalProperties: MutableMap, + ) { + @JsonCreator + private constructor( + @JsonProperty("count") + @ExcludeMissing + count: JsonField = JsonMissing.of(), + @JsonProperty("offset") + @ExcludeMissing + offset: JsonField = JsonMissing.of(), + ) : this(count, offset, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun count(): Optional = count.getOptional("count") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun offset(): Optional = offset.getOptional("offset") + + /** + * Returns the raw JSON value of [count]. + * + * Unlike [count], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("count") @ExcludeMissing fun _count(): JsonField = count + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Paging = apply { - if (validated) { - return@apply - } - - count() - offset() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Paging]. */ @JvmStatic fun builder() = Builder() } @@ -2136,10 +3532,24 @@ private constructor( fun count(count: Boolean) = count(JsonField.of(count)) + /** + * Sets [Builder.count] to an arbitrary JSON value. + * + * You should usually call [Builder.count] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun count(count: JsonField) = apply { this.count = count } fun offset(offset: Boolean) = offset(JsonField.of(offset)) + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun offset(offset: JsonField) = apply { this.offset = offset } fun additionalProperties(additionalProperties: Map) = @@ -2164,10 +3574,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Paging]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Paging = - Paging(count, offset, additionalProperties.toImmutable()) + Paging(count, offset, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Paging = apply { + if (validated) { + return@apply + } + + count() + offset() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (count.asKnown().isPresent) 1 else 0) + + (if (offset.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2204,210 +3650,384 @@ private constructor( "SupportedDirectoryFields{individuals=$individuals, paging=$paging, additionalProperties=$additionalProperties}" } - @NoAutoDetect class SupportedEmploymentFields - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("class_code") - @ExcludeMissing - private val classCode: JsonField = JsonMissing.of(), - @JsonProperty("custom_fields") - @ExcludeMissing - private val customFields: JsonField = JsonMissing.of(), - @JsonProperty("department") - @ExcludeMissing - private val department: JsonField = JsonMissing.of(), - @JsonProperty("employment") - @ExcludeMissing - private val employment: JsonField = JsonMissing.of(), - @JsonProperty("employment_status") - @ExcludeMissing - private val employmentStatus: JsonField = JsonMissing.of(), - @JsonProperty("end_date") - @ExcludeMissing - private val endDate: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("income") - @ExcludeMissing - private val income: JsonField = JsonMissing.of(), - @JsonProperty("income_history") - @ExcludeMissing - private val incomeHistory: JsonField = JsonMissing.of(), - @JsonProperty("is_active") - @ExcludeMissing - private val isActive: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), - @JsonProperty("location") - @ExcludeMissing - private val location: JsonField = JsonMissing.of(), - @JsonProperty("manager") - @ExcludeMissing - private val manager: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), - @JsonProperty("start_date") - @ExcludeMissing - private val startDate: JsonField = JsonMissing.of(), - @JsonProperty("title") - @ExcludeMissing - private val title: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val classCode: JsonField, + private val customFields: JsonField, + private val department: JsonField, + private val employment: JsonField, + private val employmentStatus: JsonField, + private val endDate: JsonField, + private val firstName: JsonField, + private val income: JsonField, + private val incomeHistory: JsonField, + private val isActive: JsonField, + private val lastName: JsonField, + private val location: JsonField, + private val manager: JsonField, + private val middleName: JsonField, + private val startDate: JsonField, + private val title: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun classCode(): Optional = - Optional.ofNullable(classCode.getNullable("class_code")) - - fun customFields(): Optional = - Optional.ofNullable(customFields.getNullable("custom_fields")) - - fun department(): Optional = - Optional.ofNullable(department.getNullable("department")) - - fun employment(): Optional = - Optional.ofNullable(employment.getNullable("employment")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("class_code") + @ExcludeMissing + classCode: JsonField = JsonMissing.of(), + @JsonProperty("custom_fields") + @ExcludeMissing + customFields: JsonField = JsonMissing.of(), + @JsonProperty("department") + @ExcludeMissing + department: JsonField = JsonMissing.of(), + @JsonProperty("employment") + @ExcludeMissing + employment: JsonField = JsonMissing.of(), + @JsonProperty("employment_status") + @ExcludeMissing + employmentStatus: JsonField = JsonMissing.of(), + @JsonProperty("end_date") + @ExcludeMissing + endDate: JsonField = JsonMissing.of(), + @JsonProperty("first_name") + @ExcludeMissing + firstName: JsonField = JsonMissing.of(), + @JsonProperty("income") + @ExcludeMissing + income: JsonField = JsonMissing.of(), + @JsonProperty("income_history") + @ExcludeMissing + incomeHistory: JsonField = JsonMissing.of(), + @JsonProperty("is_active") + @ExcludeMissing + isActive: JsonField = JsonMissing.of(), + @JsonProperty("last_name") + @ExcludeMissing + lastName: JsonField = JsonMissing.of(), + @JsonProperty("location") + @ExcludeMissing + location: JsonField = JsonMissing.of(), + @JsonProperty("manager") + @ExcludeMissing + manager: JsonField = JsonMissing.of(), + @JsonProperty("middle_name") + @ExcludeMissing + middleName: JsonField = JsonMissing.of(), + @JsonProperty("start_date") + @ExcludeMissing + startDate: JsonField = JsonMissing.of(), + @JsonProperty("title") + @ExcludeMissing + title: JsonField = JsonMissing.of(), + ) : this( + id, + classCode, + customFields, + department, + employment, + employmentStatus, + endDate, + firstName, + income, + incomeHistory, + isActive, + lastName, + location, + manager, + middleName, + startDate, + title, + mutableMapOf(), + ) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun classCode(): Optional = classCode.getOptional("class_code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun customFields(): Optional = customFields.getOptional("custom_fields") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun department(): Optional = department.getOptional("department") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun employment(): Optional = employment.getOptional("employment") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ fun employmentStatus(): Optional = - Optional.ofNullable(employmentStatus.getNullable("employment_status")) - - fun endDate(): Optional = - Optional.ofNullable(endDate.getNullable("end_date")) - - fun firstName(): Optional = - Optional.ofNullable(firstName.getNullable("first_name")) - - fun income(): Optional = Optional.ofNullable(income.getNullable("income")) - - fun incomeHistory(): Optional = - Optional.ofNullable(incomeHistory.getNullable("income_history")) - - fun isActive(): Optional = - Optional.ofNullable(isActive.getNullable("is_active")) - - fun lastName(): Optional = - Optional.ofNullable(lastName.getNullable("last_name")) - - fun location(): Optional = - Optional.ofNullable(location.getNullable("location")) - - fun manager(): Optional = - Optional.ofNullable(manager.getNullable("manager")) - - fun middleName(): Optional = - Optional.ofNullable(middleName.getNullable("middle_name")) - - fun startDate(): Optional = - Optional.ofNullable(startDate.getNullable("start_date")) - - fun title(): Optional = Optional.ofNullable(title.getNullable("title")) - + employmentStatus.getOptional("employment_status") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun endDate(): Optional = endDate.getOptional("end_date") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun income(): Optional = income.getOptional("income") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun incomeHistory(): Optional = incomeHistory.getOptional("income_history") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun isActive(): Optional = isActive.getOptional("is_active") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun location(): Optional = location.getOptional("location") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun manager(): Optional = manager.getOptional("manager") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun startDate(): Optional = startDate.getOptional("start_date") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun title(): Optional = title.getOptional("title") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [classCode]. + * + * Unlike [classCode], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("class_code") @ExcludeMissing fun _classCode(): JsonField = classCode + /** + * Returns the raw JSON value of [customFields]. + * + * Unlike [customFields], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("custom_fields") @ExcludeMissing fun _customFields(): JsonField = customFields + /** + * Returns the raw JSON value of [department]. + * + * Unlike [department], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("department") @ExcludeMissing fun _department(): JsonField = department + /** + * Returns the raw JSON value of [employment]. + * + * Unlike [employment], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("employment") @ExcludeMissing fun _employment(): JsonField = employment + /** + * Returns the raw JSON value of [employmentStatus]. + * + * Unlike [employmentStatus], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("employment_status") @ExcludeMissing fun _employmentStatus(): JsonField = employmentStatus + /** + * Returns the raw JSON value of [endDate]. + * + * Unlike [endDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("end_date") @ExcludeMissing fun _endDate(): JsonField = endDate + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName + /** + * Returns the raw JSON value of [income]. + * + * Unlike [income], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("income") @ExcludeMissing fun _income(): JsonField = income + /** + * Returns the raw JSON value of [incomeHistory]. + * + * Unlike [incomeHistory], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("income_history") @ExcludeMissing fun _incomeHistory(): JsonField = incomeHistory + /** + * Returns the raw JSON value of [isActive]. + * + * Unlike [isActive], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("is_active") @ExcludeMissing fun _isActive(): JsonField = isActive + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName + /** + * Returns the raw JSON value of [location]. + * + * Unlike [location], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("location") @ExcludeMissing fun _location(): JsonField = location + /** + * Returns the raw JSON value of [manager]. + * + * Unlike [manager], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("manager") @ExcludeMissing fun _manager(): JsonField = manager + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("middle_name") @ExcludeMissing fun _middleName(): JsonField = middleName + /** + * Returns the raw JSON value of [startDate]. + * + * Unlike [startDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("start_date") @ExcludeMissing fun _startDate(): JsonField = startDate + /** + * Returns the raw JSON value of [title]. + * + * Unlike [title], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("title") @ExcludeMissing fun _title(): JsonField = title + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedEmploymentFields = apply { - if (validated) { - return@apply - } - - id() - classCode() - customFields() - department().ifPresent { it.validate() } - employment().ifPresent { it.validate() } - employmentStatus() - endDate() - firstName() - income().ifPresent { it.validate() } - incomeHistory() - isActive() - lastName() - location().ifPresent { it.validate() } - manager().ifPresent { it.validate() } - middleName() - startDate() - title() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedEmploymentFields]. + */ @JvmStatic fun builder() = Builder() } @@ -2459,10 +4079,24 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun classCode(classCode: Boolean) = classCode(JsonField.of(classCode)) + /** + * Sets [Builder.classCode] to an arbitrary JSON value. + * + * You should usually call [Builder.classCode] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun classCode(classCode: JsonField) = apply { this.classCode = classCode } @@ -2470,18 +4104,39 @@ private constructor( fun customFields(customFields: Boolean) = customFields(JsonField.of(customFields)) + /** + * Sets [Builder.customFields] to an arbitrary JSON value. + * + * You should usually call [Builder.customFields] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun customFields(customFields: JsonField) = apply { this.customFields = customFields } fun department(department: Department) = department(JsonField.of(department)) + /** + * Sets [Builder.department] to an arbitrary JSON value. + * + * You should usually call [Builder.department] with a well-typed [Department] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun department(department: JsonField) = apply { this.department = department } fun employment(employment: Employment) = employment(JsonField.of(employment)) + /** + * Sets [Builder.employment] to an arbitrary JSON value. + * + * You should usually call [Builder.employment] with a well-typed [Employment] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun employment(employment: JsonField) = apply { this.employment = employment } @@ -2489,61 +4144,145 @@ private constructor( fun employmentStatus(employmentStatus: Boolean) = employmentStatus(JsonField.of(employmentStatus)) + /** + * Sets [Builder.employmentStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.employmentStatus] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun employmentStatus(employmentStatus: JsonField) = apply { this.employmentStatus = employmentStatus } fun endDate(endDate: Boolean) = endDate(JsonField.of(endDate)) + /** + * Sets [Builder.endDate] to an arbitrary JSON value. + * + * You should usually call [Builder.endDate] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun endDate(endDate: JsonField) = apply { this.endDate = endDate } fun firstName(firstName: Boolean) = firstName(JsonField.of(firstName)) + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun firstName(firstName: JsonField) = apply { this.firstName = firstName } fun income(income: Income) = income(JsonField.of(income)) + /** + * Sets [Builder.income] to an arbitrary JSON value. + * + * You should usually call [Builder.income] with a well-typed [Income] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun income(income: JsonField) = apply { this.income = income } fun incomeHistory(incomeHistory: Boolean) = incomeHistory(JsonField.of(incomeHistory)) + /** + * Sets [Builder.incomeHistory] to an arbitrary JSON value. + * + * You should usually call [Builder.incomeHistory] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun incomeHistory(incomeHistory: JsonField) = apply { this.incomeHistory = incomeHistory } fun isActive(isActive: Boolean) = isActive(JsonField.of(isActive)) + /** + * Sets [Builder.isActive] to an arbitrary JSON value. + * + * You should usually call [Builder.isActive] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun isActive(isActive: JsonField) = apply { this.isActive = isActive } fun lastName(lastName: Boolean) = lastName(JsonField.of(lastName)) + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun lastName(lastName: JsonField) = apply { this.lastName = lastName } fun location(location: Location) = location(JsonField.of(location)) + /** + * Sets [Builder.location] to an arbitrary JSON value. + * + * You should usually call [Builder.location] with a well-typed [Location] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun location(location: JsonField) = apply { this.location = location } fun manager(manager: Manager) = manager(JsonField.of(manager)) + /** + * Sets [Builder.manager] to an arbitrary JSON value. + * + * You should usually call [Builder.manager] with a well-typed [Manager] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun manager(manager: JsonField) = apply { this.manager = manager } fun middleName(middleName: Boolean) = middleName(JsonField.of(middleName)) + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun middleName(middleName: JsonField) = apply { this.middleName = middleName } fun startDate(startDate: Boolean) = startDate(JsonField.of(startDate)) + /** + * Sets [Builder.startDate] to an arbitrary JSON value. + * + * You should usually call [Builder.startDate] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun startDate(startDate: JsonField) = apply { this.startDate = startDate } fun title(title: Boolean) = title(JsonField.of(title)) + /** + * Sets [Builder.title] to an arbitrary JSON value. + * + * You should usually call [Builder.title] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun title(title: JsonField) = apply { this.title = title } fun additionalProperties(additionalProperties: Map) = apply { @@ -2568,6 +4307,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedEmploymentFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedEmploymentFields = SupportedEmploymentFields( id, @@ -2587,44 +4331,115 @@ private constructor( middleName, startDate, title, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): SupportedEmploymentFields = apply { + if (validated) { + return@apply + } + + id() + classCode() + customFields() + department().ifPresent { it.validate() } + employment().ifPresent { it.validate() } + employmentStatus() + endDate() + firstName() + income().ifPresent { it.validate() } + incomeHistory() + isActive() + lastName() + location().ifPresent { it.validate() } + manager().ifPresent { it.validate() } + middleName() + startDate() + title() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (classCode.asKnown().isPresent) 1 else 0) + + (if (customFields.asKnown().isPresent) 1 else 0) + + (department.asKnown().getOrNull()?.validity() ?: 0) + + (employment.asKnown().getOrNull()?.validity() ?: 0) + + (if (employmentStatus.asKnown().isPresent) 1 else 0) + + (if (endDate.asKnown().isPresent) 1 else 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (income.asKnown().getOrNull()?.validity() ?: 0) + + (if (incomeHistory.asKnown().isPresent) 1 else 0) + + (if (isActive.asKnown().isPresent) 1 else 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (location.asKnown().getOrNull()?.validity() ?: 0) + + (manager.asKnown().getOrNull()?.validity() ?: 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + + (if (startDate.asKnown().isPresent) 1 else 0) + + (if (title.asKnown().isPresent) 1 else 0) + class Department - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - + @JsonCreator + private constructor( + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Department = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Department]. + */ @JvmStatic fun builder() = Builder() } @@ -2643,6 +4458,13 @@ private constructor( fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = @@ -2667,10 +4489,43 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Department]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Department = - Department(name, additionalProperties.toImmutable()) + Department(name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Department = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2689,51 +4544,70 @@ private constructor( "Department{name=$name, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Employment - @JsonCreator private constructor( - @JsonProperty("subtype") - @ExcludeMissing - private val subtype: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val subtype: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun subtype(): Optional = - Optional.ofNullable(subtype.getNullable("subtype")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - + @JsonCreator + private constructor( + @JsonProperty("subtype") + @ExcludeMissing + subtype: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(subtype, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun subtype(): Optional = subtype.getOptional("subtype") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [subtype]. + * + * Unlike [subtype], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Employment = apply { - if (validated) { - return@apply - } - - subtype() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Employment]. + */ @JvmStatic fun builder() = Builder() } @@ -2754,10 +4628,24 @@ private constructor( fun subtype(subtype: Boolean) = subtype(JsonField.of(subtype)) + /** + * Sets [Builder.subtype] to an arbitrary JSON value. + * + * You should usually call [Builder.subtype] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun subtype(subtype: JsonField) = apply { this.subtype = subtype } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = @@ -2778,13 +4666,49 @@ private constructor( additionalProperties.remove(key) } - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Employment]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Employment = + Employment(subtype, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Employment = apply { + if (validated) { + return@apply + } + + subtype() + type() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false } - fun build(): Employment = - Employment(subtype, type, additionalProperties.toImmutable()) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (subtype.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) override fun equals(other: Any?): Boolean { if (this === other) { @@ -2804,62 +4728,88 @@ private constructor( "Employment{subtype=$subtype, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Income - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("unit") - @ExcludeMissing - private val unit: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val amount: JsonField, + private val currency: JsonField, + private val unit: JsonField, + private val additionalProperties: MutableMap, ) { - fun amount(): Optional = - Optional.ofNullable(amount.getNullable("amount")) - - fun currency(): Optional = - Optional.ofNullable(currency.getNullable("currency")) - - fun unit(): Optional = Optional.ofNullable(unit.getNullable("unit")) - + @JsonCreator + private constructor( + @JsonProperty("amount") + @ExcludeMissing + amount: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("unit") + @ExcludeMissing + unit: JsonField = JsonMissing.of(), + ) : this(amount, currency, unit, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun unit(): Optional = unit.getOptional("unit") + + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency + /** + * Returns the raw JSON value of [unit]. + * + * Unlike [unit], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("unit") @ExcludeMissing fun _unit(): JsonField = unit + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Income = apply { - if (validated) { - return@apply - } - - amount() - currency() - unit() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Income]. */ @JvmStatic fun builder() = Builder() } @@ -2882,16 +4832,37 @@ private constructor( fun amount(amount: Boolean) = amount(JsonField.of(amount)) + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun currency(currency: Boolean) = currency(JsonField.of(currency)) + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } fun unit(unit: Boolean) = unit(JsonField.of(unit)) + /** + * Sets [Builder.unit] to an arbitrary JSON value. + * + * You should usually call [Builder.unit] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun unit(unit: JsonField) = apply { this.unit = unit } fun additionalProperties(additionalProperties: Map) = @@ -2916,10 +4887,48 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Income]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Income = - Income(amount, currency, unit, additionalProperties.toImmutable()) + Income(amount, currency, unit, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Income = apply { + if (validated) { + return@apply + } + + amount() + currency() + unit() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (unit.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2938,86 +4947,142 @@ private constructor( "Income{amount=$amount, currency=$currency, unit=$unit, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Location - @JsonCreator private constructor( - @JsonProperty("city") - @ExcludeMissing - private val city: JsonField = JsonMissing.of(), - @JsonProperty("country") - @ExcludeMissing - private val country: JsonField = JsonMissing.of(), - @JsonProperty("line1") - @ExcludeMissing - private val line1: JsonField = JsonMissing.of(), - @JsonProperty("line2") - @ExcludeMissing - private val line2: JsonField = JsonMissing.of(), - @JsonProperty("postal_code") - @ExcludeMissing - private val postalCode: JsonField = JsonMissing.of(), - @JsonProperty("state") - @ExcludeMissing - private val state: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val city: JsonField, + private val country: JsonField, + private val line1: JsonField, + private val line2: JsonField, + private val postalCode: JsonField, + private val state: JsonField, + private val additionalProperties: MutableMap, ) { - fun city(): Optional = Optional.ofNullable(city.getNullable("city")) - - fun country(): Optional = - Optional.ofNullable(country.getNullable("country")) - - fun line1(): Optional = Optional.ofNullable(line1.getNullable("line1")) - - fun line2(): Optional = Optional.ofNullable(line2.getNullable("line2")) - - fun postalCode(): Optional = - Optional.ofNullable(postalCode.getNullable("postal_code")) - - fun state(): Optional = Optional.ofNullable(state.getNullable("state")) - + @JsonCreator + private constructor( + @JsonProperty("city") + @ExcludeMissing + city: JsonField = JsonMissing.of(), + @JsonProperty("country") + @ExcludeMissing + country: JsonField = JsonMissing.of(), + @JsonProperty("line1") + @ExcludeMissing + line1: JsonField = JsonMissing.of(), + @JsonProperty("line2") + @ExcludeMissing + line2: JsonField = JsonMissing.of(), + @JsonProperty("postal_code") + @ExcludeMissing + postalCode: JsonField = JsonMissing.of(), + @JsonProperty("state") + @ExcludeMissing + state: JsonField = JsonMissing.of(), + ) : this(city, country, line1, line2, postalCode, state, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun city(): Optional = city.getOptional("city") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun country(): Optional = country.getOptional("country") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun line1(): Optional = line1.getOptional("line1") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun line2(): Optional = line2.getOptional("line2") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun postalCode(): Optional = postalCode.getOptional("postal_code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun state(): Optional = state.getOptional("state") + + /** + * Returns the raw JSON value of [city]. + * + * Unlike [city], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("city") @ExcludeMissing fun _city(): JsonField = city + /** + * Returns the raw JSON value of [country]. + * + * Unlike [country], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("country") @ExcludeMissing fun _country(): JsonField = country + /** + * Returns the raw JSON value of [line1]. + * + * Unlike [line1], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("line1") @ExcludeMissing fun _line1(): JsonField = line1 + /** + * Returns the raw JSON value of [line2]. + * + * Unlike [line2], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("line2") @ExcludeMissing fun _line2(): JsonField = line2 + /** + * Returns the raw JSON value of [postalCode]. + * + * Unlike [postalCode], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("postal_code") @ExcludeMissing fun _postalCode(): JsonField = postalCode + /** + * Returns the raw JSON value of [state]. + * + * Unlike [state], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("state") @ExcludeMissing fun _state(): JsonField = state + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Location = apply { - if (validated) { - return@apply - } - - city() - country() - line1() - line2() - postalCode() - state() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Location]. */ @JvmStatic fun builder() = Builder() } @@ -3046,28 +5111,70 @@ private constructor( fun city(city: Boolean) = city(JsonField.of(city)) + /** + * Sets [Builder.city] to an arbitrary JSON value. + * + * You should usually call [Builder.city] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun city(city: JsonField) = apply { this.city = city } fun country(country: Boolean) = country(JsonField.of(country)) + /** + * Sets [Builder.country] to an arbitrary JSON value. + * + * You should usually call [Builder.country] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun country(country: JsonField) = apply { this.country = country } fun line1(line1: Boolean) = line1(JsonField.of(line1)) + /** + * Sets [Builder.line1] to an arbitrary JSON value. + * + * You should usually call [Builder.line1] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun line1(line1: JsonField) = apply { this.line1 = line1 } fun line2(line2: Boolean) = line2(JsonField.of(line2)) + /** + * Sets [Builder.line2] to an arbitrary JSON value. + * + * You should usually call [Builder.line2] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun line2(line2: JsonField) = apply { this.line2 = line2 } fun postalCode(postalCode: Boolean) = postalCode(JsonField.of(postalCode)) + /** + * Sets [Builder.postalCode] to an arbitrary JSON value. + * + * You should usually call [Builder.postalCode] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun postalCode(postalCode: JsonField) = apply { this.postalCode = postalCode } fun state(state: Boolean) = state(JsonField.of(state)) + /** + * Sets [Builder.state] to an arbitrary JSON value. + * + * You should usually call [Builder.state] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun state(state: JsonField) = apply { this.state = state } fun additionalProperties(additionalProperties: Map) = @@ -3092,6 +5199,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Location]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Location = Location( city, @@ -3100,10 +5212,49 @@ private constructor( line2, postalCode, state, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Location = apply { + if (validated) { + return@apply + } + + city() + country() + line1() + line2() + postalCode() + state() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (city.asKnown().isPresent) 1 else 0) + + (if (country.asKnown().isPresent) 1 else 0) + + (if (line1.asKnown().isPresent) 1 else 0) + + (if (line2.asKnown().isPresent) 1 else 0) + + (if (postalCode.asKnown().isPresent) 1 else 0) + + (if (state.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3122,40 +5273,48 @@ private constructor( "Location{city=$city, country=$country, line1=$line1, line2=$line2, postalCode=$postalCode, state=$state, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Manager - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - + @JsonCreator + private constructor( + @JsonProperty("id") + @ExcludeMissing + id: JsonField = JsonMissing.of() + ) : this(id, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Manager = apply { - if (validated) { - return@apply - } - - id() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Manager]. */ @JvmStatic fun builder() = Builder() } @@ -3174,6 +5333,13 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun additionalProperties(additionalProperties: Map) = @@ -3198,9 +5364,42 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Manager = Manager(id, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Manager]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Manager = Manager(id, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Manager = apply { + if (validated) { + return@apply + } + + id() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (if (id.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3237,160 +5436,290 @@ private constructor( "SupportedEmploymentFields{id=$id, classCode=$classCode, customFields=$customFields, department=$department, employment=$employment, employmentStatus=$employmentStatus, endDate=$endDate, firstName=$firstName, income=$income, incomeHistory=$incomeHistory, isActive=$isActive, lastName=$lastName, location=$location, manager=$manager, middleName=$middleName, startDate=$startDate, title=$title, additionalProperties=$additionalProperties}" } - @NoAutoDetect class SupportedIndividualFields - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("dob") - @ExcludeMissing - private val dob: JsonField = JsonMissing.of(), - @JsonProperty("emails") - @ExcludeMissing - private val emails: JsonField = JsonMissing.of(), - @JsonProperty("encrypted_ssn") - @ExcludeMissing - private val encryptedSsn: JsonField = JsonMissing.of(), - @JsonProperty("ethnicity") - @ExcludeMissing - private val ethnicity: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("gender") - @ExcludeMissing - private val gender: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), - @JsonProperty("phone_numbers") - @ExcludeMissing - private val phoneNumbers: JsonField = JsonMissing.of(), - @JsonProperty("preferred_name") - @ExcludeMissing - private val preferredName: JsonField = JsonMissing.of(), - @JsonProperty("residence") - @ExcludeMissing - private val residence: JsonField = JsonMissing.of(), - @JsonProperty("ssn") - @ExcludeMissing - private val ssn: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val dob: JsonField, + private val emails: JsonField, + private val encryptedSsn: JsonField, + private val ethnicity: JsonField, + private val firstName: JsonField, + private val gender: JsonField, + private val lastName: JsonField, + private val middleName: JsonField, + private val phoneNumbers: JsonField, + private val preferredName: JsonField, + private val residence: JsonField, + private val ssn: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun dob(): Optional = Optional.ofNullable(dob.getNullable("dob")) - - fun emails(): Optional = Optional.ofNullable(emails.getNullable("emails")) - - fun encryptedSsn(): Optional = - Optional.ofNullable(encryptedSsn.getNullable("encrypted_ssn")) - - fun ethnicity(): Optional = - Optional.ofNullable(ethnicity.getNullable("ethnicity")) - - fun firstName(): Optional = - Optional.ofNullable(firstName.getNullable("first_name")) - - fun gender(): Optional = Optional.ofNullable(gender.getNullable("gender")) - - fun lastName(): Optional = - Optional.ofNullable(lastName.getNullable("last_name")) - - fun middleName(): Optional = - Optional.ofNullable(middleName.getNullable("middle_name")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("dob") @ExcludeMissing dob: JsonField = JsonMissing.of(), + @JsonProperty("emails") + @ExcludeMissing + emails: JsonField = JsonMissing.of(), + @JsonProperty("encrypted_ssn") + @ExcludeMissing + encryptedSsn: JsonField = JsonMissing.of(), + @JsonProperty("ethnicity") + @ExcludeMissing + ethnicity: JsonField = JsonMissing.of(), + @JsonProperty("first_name") + @ExcludeMissing + firstName: JsonField = JsonMissing.of(), + @JsonProperty("gender") + @ExcludeMissing + gender: JsonField = JsonMissing.of(), + @JsonProperty("last_name") + @ExcludeMissing + lastName: JsonField = JsonMissing.of(), + @JsonProperty("middle_name") + @ExcludeMissing + middleName: JsonField = JsonMissing.of(), + @JsonProperty("phone_numbers") + @ExcludeMissing + phoneNumbers: JsonField = JsonMissing.of(), + @JsonProperty("preferred_name") + @ExcludeMissing + preferredName: JsonField = JsonMissing.of(), + @JsonProperty("residence") + @ExcludeMissing + residence: JsonField = JsonMissing.of(), + @JsonProperty("ssn") @ExcludeMissing ssn: JsonField = JsonMissing.of(), + ) : this( + id, + dob, + emails, + encryptedSsn, + ethnicity, + firstName, + gender, + lastName, + middleName, + phoneNumbers, + preferredName, + residence, + ssn, + mutableMapOf(), + ) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun dob(): Optional = dob.getOptional("dob") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun emails(): Optional = emails.getOptional("emails") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun encryptedSsn(): Optional = encryptedSsn.getOptional("encrypted_ssn") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun ethnicity(): Optional = ethnicity.getOptional("ethnicity") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun gender(): Optional = gender.getOptional("gender") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ fun phoneNumbers(): Optional = - Optional.ofNullable(phoneNumbers.getNullable("phone_numbers")) - - fun preferredName(): Optional = - Optional.ofNullable(preferredName.getNullable("preferred_name")) - - fun residence(): Optional = - Optional.ofNullable(residence.getNullable("residence")) - - fun ssn(): Optional = Optional.ofNullable(ssn.getNullable("ssn")) - + phoneNumbers.getOptional("phone_numbers") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun preferredName(): Optional = preferredName.getOptional("preferred_name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun residence(): Optional = residence.getOptional("residence") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun ssn(): Optional = ssn.getOptional("ssn") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [dob]. + * + * Unlike [dob], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("dob") @ExcludeMissing fun _dob(): JsonField = dob + /** + * Returns the raw JSON value of [emails]. + * + * Unlike [emails], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("emails") @ExcludeMissing fun _emails(): JsonField = emails + /** + * Returns the raw JSON value of [encryptedSsn]. + * + * Unlike [encryptedSsn], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("encrypted_ssn") @ExcludeMissing fun _encryptedSsn(): JsonField = encryptedSsn + /** + * Returns the raw JSON value of [ethnicity]. + * + * Unlike [ethnicity], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("ethnicity") @ExcludeMissing fun _ethnicity(): JsonField = ethnicity + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName + /** + * Returns the raw JSON value of [gender]. + * + * Unlike [gender], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("gender") @ExcludeMissing fun _gender(): JsonField = gender + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("middle_name") @ExcludeMissing fun _middleName(): JsonField = middleName + /** + * Returns the raw JSON value of [phoneNumbers]. + * + * Unlike [phoneNumbers], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("phone_numbers") @ExcludeMissing fun _phoneNumbers(): JsonField = phoneNumbers + /** + * Returns the raw JSON value of [preferredName]. + * + * Unlike [preferredName], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("preferred_name") @ExcludeMissing fun _preferredName(): JsonField = preferredName + /** + * Returns the raw JSON value of [residence]. + * + * Unlike [residence], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("residence") @ExcludeMissing fun _residence(): JsonField = residence + /** + * Returns the raw JSON value of [ssn]. + * + * Unlike [ssn], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("ssn") @ExcludeMissing fun _ssn(): JsonField = ssn + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedIndividualFields = apply { - if (validated) { - return@apply - } - - id() - dob() - emails().ifPresent { it.validate() } - encryptedSsn() - ethnicity() - firstName() - gender() - lastName() - middleName() - phoneNumbers().ifPresent { it.validate() } - preferredName() - residence().ifPresent { it.validate() } - ssn() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedIndividualFields]. + */ @JvmStatic fun builder() = Builder() } @@ -3434,45 +5763,108 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun dob(dob: Boolean) = dob(JsonField.of(dob)) + /** + * Sets [Builder.dob] to an arbitrary JSON value. + * + * You should usually call [Builder.dob] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun dob(dob: JsonField) = apply { this.dob = dob } fun emails(emails: Emails) = emails(JsonField.of(emails)) + /** + * Sets [Builder.emails] to an arbitrary JSON value. + * + * You should usually call [Builder.emails] with a well-typed [Emails] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun emails(emails: JsonField) = apply { this.emails = emails } fun encryptedSsn(encryptedSsn: Boolean) = encryptedSsn(JsonField.of(encryptedSsn)) + /** + * Sets [Builder.encryptedSsn] to an arbitrary JSON value. + * + * You should usually call [Builder.encryptedSsn] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun encryptedSsn(encryptedSsn: JsonField) = apply { this.encryptedSsn = encryptedSsn } fun ethnicity(ethnicity: Boolean) = ethnicity(JsonField.of(ethnicity)) + /** + * Sets [Builder.ethnicity] to an arbitrary JSON value. + * + * You should usually call [Builder.ethnicity] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun ethnicity(ethnicity: JsonField) = apply { this.ethnicity = ethnicity } fun firstName(firstName: Boolean) = firstName(JsonField.of(firstName)) + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun firstName(firstName: JsonField) = apply { this.firstName = firstName } fun gender(gender: Boolean) = gender(JsonField.of(gender)) + /** + * Sets [Builder.gender] to an arbitrary JSON value. + * + * You should usually call [Builder.gender] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun gender(gender: JsonField) = apply { this.gender = gender } fun lastName(lastName: Boolean) = lastName(JsonField.of(lastName)) + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun lastName(lastName: JsonField) = apply { this.lastName = lastName } fun middleName(middleName: Boolean) = middleName(JsonField.of(middleName)) + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun middleName(middleName: JsonField) = apply { this.middleName = middleName } @@ -3480,6 +5872,13 @@ private constructor( fun phoneNumbers(phoneNumbers: PhoneNumbers) = phoneNumbers(JsonField.of(phoneNumbers)) + /** + * Sets [Builder.phoneNumbers] to an arbitrary JSON value. + * + * You should usually call [Builder.phoneNumbers] with a well-typed + * [PhoneNumbers] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun phoneNumbers(phoneNumbers: JsonField) = apply { this.phoneNumbers = phoneNumbers } @@ -3487,18 +5886,39 @@ private constructor( fun preferredName(preferredName: Boolean) = preferredName(JsonField.of(preferredName)) + /** + * Sets [Builder.preferredName] to an arbitrary JSON value. + * + * You should usually call [Builder.preferredName] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun preferredName(preferredName: JsonField) = apply { this.preferredName = preferredName } fun residence(residence: Residence) = residence(JsonField.of(residence)) + /** + * Sets [Builder.residence] to an arbitrary JSON value. + * + * You should usually call [Builder.residence] with a well-typed [Residence] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun residence(residence: JsonField) = apply { this.residence = residence } fun ssn(ssn: Boolean) = ssn(JsonField.of(ssn)) + /** + * Sets [Builder.ssn] to an arbitrary JSON value. + * + * You should usually call [Builder.ssn] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun ssn(ssn: JsonField) = apply { this.ssn = ssn } fun additionalProperties(additionalProperties: Map) = apply { @@ -3523,6 +5943,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedIndividualFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedIndividualFields = SupportedIndividualFields( id, @@ -3538,52 +5963,123 @@ private constructor( preferredName, residence, ssn, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): SupportedIndividualFields = apply { + if (validated) { + return@apply + } + + id() + dob() + emails().ifPresent { it.validate() } + encryptedSsn() + ethnicity() + firstName() + gender() + lastName() + middleName() + phoneNumbers().ifPresent { it.validate() } + preferredName() + residence().ifPresent { it.validate() } + ssn() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (dob.asKnown().isPresent) 1 else 0) + + (emails.asKnown().getOrNull()?.validity() ?: 0) + + (if (encryptedSsn.asKnown().isPresent) 1 else 0) + + (if (ethnicity.asKnown().isPresent) 1 else 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (if (gender.asKnown().isPresent) 1 else 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + + (phoneNumbers.asKnown().getOrNull()?.validity() ?: 0) + + (if (preferredName.asKnown().isPresent) 1 else 0) + + (residence.asKnown().getOrNull()?.validity() ?: 0) + + (if (ssn.asKnown().isPresent) 1 else 0) + class Emails - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - + @JsonCreator + private constructor( + @JsonProperty("data") + @ExcludeMissing + data: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Emails = apply { - if (validated) { - return@apply - } - - data() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Emails]. */ @JvmStatic fun builder() = Builder() } @@ -3604,10 +6100,24 @@ private constructor( fun data(data: Boolean) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = @@ -3632,9 +6142,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Emails = Emails(data, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Emails]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Emails = + Emails(data, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Emails = apply { + if (validated) { + return@apply + } + + data() + type() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3653,48 +6200,68 @@ private constructor( "Emails{data=$data, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class PhoneNumbers - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - + @JsonCreator + private constructor( + @JsonProperty("data") + @ExcludeMissing + data: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PhoneNumbers = apply { - if (validated) { - return@apply - } - - data() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [PhoneNumbers]. + */ @JvmStatic fun builder() = Builder() } @@ -3715,10 +6282,24 @@ private constructor( fun data(data: Boolean) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = @@ -3743,10 +6324,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PhoneNumbers]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): PhoneNumbers = - PhoneNumbers(data, type, additionalProperties.toImmutable()) + PhoneNumbers(data, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): PhoneNumbers = apply { + if (validated) { + return@apply + } + + data() + type() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3765,86 +6382,144 @@ private constructor( "PhoneNumbers{data=$data, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Residence - @JsonCreator private constructor( - @JsonProperty("city") - @ExcludeMissing - private val city: JsonField = JsonMissing.of(), - @JsonProperty("country") - @ExcludeMissing - private val country: JsonField = JsonMissing.of(), - @JsonProperty("line1") - @ExcludeMissing - private val line1: JsonField = JsonMissing.of(), - @JsonProperty("line2") - @ExcludeMissing - private val line2: JsonField = JsonMissing.of(), - @JsonProperty("postal_code") - @ExcludeMissing - private val postalCode: JsonField = JsonMissing.of(), - @JsonProperty("state") - @ExcludeMissing - private val state: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val city: JsonField, + private val country: JsonField, + private val line1: JsonField, + private val line2: JsonField, + private val postalCode: JsonField, + private val state: JsonField, + private val additionalProperties: MutableMap, ) { - fun city(): Optional = Optional.ofNullable(city.getNullable("city")) - - fun country(): Optional = - Optional.ofNullable(country.getNullable("country")) - - fun line1(): Optional = Optional.ofNullable(line1.getNullable("line1")) - - fun line2(): Optional = Optional.ofNullable(line2.getNullable("line2")) - - fun postalCode(): Optional = - Optional.ofNullable(postalCode.getNullable("postal_code")) - - fun state(): Optional = Optional.ofNullable(state.getNullable("state")) - + @JsonCreator + private constructor( + @JsonProperty("city") + @ExcludeMissing + city: JsonField = JsonMissing.of(), + @JsonProperty("country") + @ExcludeMissing + country: JsonField = JsonMissing.of(), + @JsonProperty("line1") + @ExcludeMissing + line1: JsonField = JsonMissing.of(), + @JsonProperty("line2") + @ExcludeMissing + line2: JsonField = JsonMissing.of(), + @JsonProperty("postal_code") + @ExcludeMissing + postalCode: JsonField = JsonMissing.of(), + @JsonProperty("state") + @ExcludeMissing + state: JsonField = JsonMissing.of(), + ) : this(city, country, line1, line2, postalCode, state, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun city(): Optional = city.getOptional("city") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun country(): Optional = country.getOptional("country") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun line1(): Optional = line1.getOptional("line1") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun line2(): Optional = line2.getOptional("line2") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun postalCode(): Optional = postalCode.getOptional("postal_code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun state(): Optional = state.getOptional("state") + + /** + * Returns the raw JSON value of [city]. + * + * Unlike [city], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("city") @ExcludeMissing fun _city(): JsonField = city + /** + * Returns the raw JSON value of [country]. + * + * Unlike [country], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("country") @ExcludeMissing fun _country(): JsonField = country + /** + * Returns the raw JSON value of [line1]. + * + * Unlike [line1], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("line1") @ExcludeMissing fun _line1(): JsonField = line1 + /** + * Returns the raw JSON value of [line2]. + * + * Unlike [line2], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("line2") @ExcludeMissing fun _line2(): JsonField = line2 + /** + * Returns the raw JSON value of [postalCode]. + * + * Unlike [postalCode], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("postal_code") @ExcludeMissing fun _postalCode(): JsonField = postalCode + /** + * Returns the raw JSON value of [state]. + * + * Unlike [state], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("state") @ExcludeMissing fun _state(): JsonField = state + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Residence = apply { - if (validated) { - return@apply - } - - city() - country() - line1() - line2() - postalCode() - state() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Residence]. + */ @JvmStatic fun builder() = Builder() } @@ -3873,28 +6548,70 @@ private constructor( fun city(city: Boolean) = city(JsonField.of(city)) + /** + * Sets [Builder.city] to an arbitrary JSON value. + * + * You should usually call [Builder.city] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun city(city: JsonField) = apply { this.city = city } fun country(country: Boolean) = country(JsonField.of(country)) + /** + * Sets [Builder.country] to an arbitrary JSON value. + * + * You should usually call [Builder.country] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun country(country: JsonField) = apply { this.country = country } fun line1(line1: Boolean) = line1(JsonField.of(line1)) + /** + * Sets [Builder.line1] to an arbitrary JSON value. + * + * You should usually call [Builder.line1] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun line1(line1: JsonField) = apply { this.line1 = line1 } fun line2(line2: Boolean) = line2(JsonField.of(line2)) + /** + * Sets [Builder.line2] to an arbitrary JSON value. + * + * You should usually call [Builder.line2] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun line2(line2: JsonField) = apply { this.line2 = line2 } fun postalCode(postalCode: Boolean) = postalCode(JsonField.of(postalCode)) + /** + * Sets [Builder.postalCode] to an arbitrary JSON value. + * + * You should usually call [Builder.postalCode] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun postalCode(postalCode: JsonField) = apply { this.postalCode = postalCode } fun state(state: Boolean) = state(JsonField.of(state)) + /** + * Sets [Builder.state] to an arbitrary JSON value. + * + * You should usually call [Builder.state] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun state(state: JsonField) = apply { this.state = state } fun additionalProperties(additionalProperties: Map) = @@ -3919,6 +6636,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Residence]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Residence = Residence( city, @@ -3927,10 +6649,49 @@ private constructor( line2, postalCode, state, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Residence = apply { + if (validated) { + return@apply + } + + city() + country() + line1() + line2() + postalCode() + state() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (city.asKnown().isPresent) 1 else 0) + + (if (country.asKnown().isPresent) 1 else 0) + + (if (line1.asKnown().isPresent) 1 else 0) + + (if (line2.asKnown().isPresent) 1 else 0) + + (if (postalCode.asKnown().isPresent) 1 else 0) + + (if (state.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3967,70 +6728,107 @@ private constructor( "SupportedIndividualFields{id=$id, dob=$dob, emails=$emails, encryptedSsn=$encryptedSsn, ethnicity=$ethnicity, firstName=$firstName, gender=$gender, lastName=$lastName, middleName=$middleName, phoneNumbers=$phoneNumbers, preferredName=$preferredName, residence=$residence, ssn=$ssn, additionalProperties=$additionalProperties}" } - @NoAutoDetect class SupportedPayGroupFields - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("individual_ids") - @ExcludeMissing - private val individualIds: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("pay_frequencies") - @ExcludeMissing - private val payFrequencies: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val individualIds: JsonField, + private val name: JsonField, + private val payFrequencies: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun individualIds(): Optional = - Optional.ofNullable(individualIds.getNullable("individual_ids")) - - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("individual_ids") + @ExcludeMissing + individualIds: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("pay_frequencies") + @ExcludeMissing + payFrequencies: JsonField = JsonMissing.of(), + ) : this(id, individualIds, name, payFrequencies, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun individualIds(): Optional = individualIds.getOptional("individual_ids") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ fun payFrequencies(): Optional = - Optional.ofNullable(payFrequencies.getNullable("pay_frequencies")) + payFrequencies.getOptional("pay_frequencies") + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [individualIds]. + * + * Unlike [individualIds], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("individual_ids") @ExcludeMissing fun _individualIds(): JsonField = individualIds + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + /** + * Returns the raw JSON value of [payFrequencies]. + * + * Unlike [payFrequencies], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("pay_frequencies") @ExcludeMissing fun _payFrequencies(): JsonField = payFrequencies + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedPayGroupFields = apply { - if (validated) { - return@apply - } - - id() - individualIds() - name() - payFrequencies() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedPayGroupFields]. + */ @JvmStatic fun builder() = Builder() } @@ -4055,22 +6853,50 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun individualIds(individualIds: Boolean) = individualIds(JsonField.of(individualIds)) + /** + * Sets [Builder.individualIds] to an arbitrary JSON value. + * + * You should usually call [Builder.individualIds] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun individualIds(individualIds: JsonField) = apply { this.individualIds = individualIds } fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun payFrequencies(payFrequencies: Boolean) = payFrequencies(JsonField.of(payFrequencies)) + /** + * Sets [Builder.payFrequencies] to an arbitrary JSON value. + * + * You should usually call [Builder.payFrequencies] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun payFrequencies(payFrequencies: JsonField) = apply { this.payFrequencies = payFrequencies } @@ -4097,16 +6923,56 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedPayGroupFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedPayGroupFields = SupportedPayGroupFields( id, individualIds, name, payFrequencies, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): SupportedPayGroupFields = apply { + if (validated) { + return@apply + } + + id() + individualIds() + name() + payFrequencies() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (individualIds.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (payFrequencies.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4125,51 +6991,72 @@ private constructor( "SupportedPayGroupFields{id=$id, individualIds=$individualIds, name=$name, payFrequencies=$payFrequencies, additionalProperties=$additionalProperties}" } - @NoAutoDetect class SupportedPayStatementFields - @JsonCreator private constructor( - @JsonProperty("paging") - @ExcludeMissing - private val paging: JsonField = JsonMissing.of(), - @JsonProperty("pay_statements") - @ExcludeMissing - private val payStatements: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val paging: JsonField, + private val payStatements: JsonField, + private val additionalProperties: MutableMap, ) { - fun paging(): Optional = Optional.ofNullable(paging.getNullable("paging")) - + @JsonCreator + private constructor( + @JsonProperty("paging") + @ExcludeMissing + paging: JsonField = JsonMissing.of(), + @JsonProperty("pay_statements") + @ExcludeMissing + payStatements: JsonField = JsonMissing.of(), + ) : this(paging, payStatements, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun paging(): Optional = paging.getOptional("paging") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ fun payStatements(): Optional = - Optional.ofNullable(payStatements.getNullable("pay_statements")) - + payStatements.getOptional("pay_statements") + + /** + * Returns the raw JSON value of [paging]. + * + * Unlike [paging], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("paging") @ExcludeMissing fun _paging(): JsonField = paging + /** + * Returns the raw JSON value of [payStatements]. + * + * Unlike [payStatements], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("pay_statements") @ExcludeMissing fun _payStatements(): JsonField = payStatements + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedPayStatementFields = apply { - if (validated) { - return@apply - } - - paging().ifPresent { it.validate() } - payStatements().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedPayStatementFields]. + */ @JvmStatic fun builder() = Builder() } @@ -4191,11 +7078,25 @@ private constructor( fun paging(paging: Paging) = paging(JsonField.of(paging)) + /** + * Sets [Builder.paging] to an arbitrary JSON value. + * + * You should usually call [Builder.paging] with a well-typed [Paging] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun paging(paging: JsonField) = apply { this.paging = paging } fun payStatements(payStatements: PayStatements) = payStatements(JsonField.of(payStatements)) + /** + * Sets [Builder.payStatements] to an arbitrary JSON value. + * + * You should usually call [Builder.payStatements] with a well-typed + * [PayStatements] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun payStatements(payStatements: JsonField) = apply { this.payStatements = payStatements } @@ -4222,58 +7123,122 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedPayStatementFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedPayStatementFields = SupportedPayStatementFields( paging, payStatements, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): SupportedPayStatementFields = apply { + if (validated) { + return@apply + } + + paging().ifPresent { it.validate() } + payStatements().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (paging.asKnown().getOrNull()?.validity() ?: 0) + + (payStatements.asKnown().getOrNull()?.validity() ?: 0) + class Paging - @JsonCreator private constructor( - @JsonProperty("count") - @ExcludeMissing - private val count: JsonField = JsonMissing.of(), - @JsonProperty("offset") - @ExcludeMissing - private val offset: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val count: JsonField, + private val offset: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("count") + @ExcludeMissing + count: JsonField = JsonMissing.of(), + @JsonProperty("offset") + @ExcludeMissing + offset: JsonField = JsonMissing.of(), + ) : this(count, offset, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ fun count(): Boolean = count.getRequired("count") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or + * is unexpectedly missing or null (e.g. if the server responded with an + * unexpected value). + */ fun offset(): Boolean = offset.getRequired("offset") + /** + * Returns the raw JSON value of [count]. + * + * Unlike [count], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("count") @ExcludeMissing fun _count(): JsonField = count + /** + * Returns the raw JSON value of [offset]. + * + * Unlike [offset], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("offset") @ExcludeMissing fun _offset(): JsonField = offset + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Paging = apply { - if (validated) { - return@apply - } - - count() - offset() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Paging]. + * + * The following fields are required: + * ```java + * .count() + * .offset() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -4294,10 +7259,24 @@ private constructor( fun count(count: Boolean) = count(JsonField.of(count)) + /** + * Sets [Builder.count] to an arbitrary JSON value. + * + * You should usually call [Builder.count] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun count(count: JsonField) = apply { this.count = count } fun offset(offset: Boolean) = offset(JsonField.of(offset)) + /** + * Sets [Builder.offset] to an arbitrary JSON value. + * + * You should usually call [Builder.offset] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun offset(offset: JsonField) = apply { this.offset = offset } fun additionalProperties(additionalProperties: Map) = @@ -4322,14 +7301,58 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Paging]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .count() + * .offset() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Paging = Paging( checkRequired("count", count), checkRequired("offset", offset), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Paging = apply { + if (validated) { + return@apply + } + + count() + offset() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (count.asKnown().isPresent) 1 else 0) + + (if (offset.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4348,141 +7371,246 @@ private constructor( "Paging{count=$count, offset=$offset, additionalProperties=$additionalProperties}" } - @NoAutoDetect class PayStatements - @JsonCreator private constructor( - @JsonProperty("earnings") - @ExcludeMissing - private val earnings: JsonField = JsonMissing.of(), - @JsonProperty("employee_deductions") - @ExcludeMissing - private val employeeDeductions: JsonField = - JsonMissing.of(), - @JsonProperty("employer_contributions") - @ExcludeMissing - private val employerContributions: JsonField = - JsonMissing.of(), - @JsonProperty("gross_pay") - @ExcludeMissing - private val grossPay: JsonField = JsonMissing.of(), - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonProperty("net_pay") - @ExcludeMissing - private val netPay: JsonField = JsonMissing.of(), - @JsonProperty("payment_method") - @ExcludeMissing - private val paymentMethod: JsonField = JsonMissing.of(), - @JsonProperty("taxes") - @ExcludeMissing - private val taxes: JsonField = JsonMissing.of(), - @JsonProperty("total_hours") - @ExcludeMissing - private val totalHours: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val earnings: JsonField, + private val employeeDeductions: JsonField, + private val employerContributions: JsonField, + private val grossPay: JsonField, + private val individualId: JsonField, + private val netPay: JsonField, + private val paymentMethod: JsonField, + private val taxes: JsonField, + private val totalHours: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun earnings(): Optional = - Optional.ofNullable(earnings.getNullable("earnings")) + @JsonCreator + private constructor( + @JsonProperty("earnings") + @ExcludeMissing + earnings: JsonField = JsonMissing.of(), + @JsonProperty("employee_deductions") + @ExcludeMissing + employeeDeductions: JsonField = JsonMissing.of(), + @JsonProperty("employer_contributions") + @ExcludeMissing + employerContributions: JsonField = JsonMissing.of(), + @JsonProperty("gross_pay") + @ExcludeMissing + grossPay: JsonField = JsonMissing.of(), + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of(), + @JsonProperty("net_pay") + @ExcludeMissing + netPay: JsonField = JsonMissing.of(), + @JsonProperty("payment_method") + @ExcludeMissing + paymentMethod: JsonField = JsonMissing.of(), + @JsonProperty("taxes") + @ExcludeMissing + taxes: JsonField = JsonMissing.of(), + @JsonProperty("total_hours") + @ExcludeMissing + totalHours: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this( + earnings, + employeeDeductions, + employerContributions, + grossPay, + individualId, + netPay, + paymentMethod, + taxes, + totalHours, + type, + mutableMapOf(), + ) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun earnings(): Optional = earnings.getOptional("earnings") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun employeeDeductions(): Optional = - Optional.ofNullable(employeeDeductions.getNullable("employee_deductions")) + employeeDeductions.getOptional("employee_deductions") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun employerContributions(): Optional = - Optional.ofNullable( - employerContributions.getNullable("employer_contributions") - ) - - fun grossPay(): Optional = - Optional.ofNullable(grossPay.getNullable("gross_pay")) - + employerContributions.getOptional("employer_contributions") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun grossPay(): Optional = grossPay.getOptional("gross_pay") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) - - fun netPay(): Optional = - Optional.ofNullable(netPay.getNullable("net_pay")) - + individualId.getOptional("individual_id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun netPay(): Optional = netPay.getOptional("net_pay") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ fun paymentMethod(): Optional = - Optional.ofNullable(paymentMethod.getNullable("payment_method")) - - fun taxes(): Optional = Optional.ofNullable(taxes.getNullable("taxes")) - - fun totalHours(): Optional = - Optional.ofNullable(totalHours.getNullable("total_hours")) - - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - + paymentMethod.getOptional("payment_method") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun taxes(): Optional = taxes.getOptional("taxes") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun totalHours(): Optional = totalHours.getOptional("total_hours") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [earnings]. + * + * Unlike [earnings], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("earnings") @ExcludeMissing fun _earnings(): JsonField = earnings + /** + * Returns the raw JSON value of [employeeDeductions]. + * + * Unlike [employeeDeductions], this method doesn't throw if the JSON field has + * an unexpected type. + */ @JsonProperty("employee_deductions") @ExcludeMissing fun _employeeDeductions(): JsonField = employeeDeductions + /** + * Returns the raw JSON value of [employerContributions]. + * + * Unlike [employerContributions], this method doesn't throw if the JSON field + * has an unexpected type. + */ @JsonProperty("employer_contributions") @ExcludeMissing fun _employerContributions(): JsonField = employerContributions + /** + * Returns the raw JSON value of [grossPay]. + * + * Unlike [grossPay], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("gross_pay") @ExcludeMissing fun _grossPay(): JsonField = grossPay + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + /** + * Returns the raw JSON value of [netPay]. + * + * Unlike [netPay], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("net_pay") @ExcludeMissing fun _netPay(): JsonField = netPay + /** + * Returns the raw JSON value of [paymentMethod]. + * + * Unlike [paymentMethod], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("payment_method") @ExcludeMissing fun _paymentMethod(): JsonField = paymentMethod + /** + * Returns the raw JSON value of [taxes]. + * + * Unlike [taxes], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("taxes") @ExcludeMissing fun _taxes(): JsonField = taxes + /** + * Returns the raw JSON value of [totalHours]. + * + * Unlike [totalHours], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("total_hours") @ExcludeMissing fun _totalHours(): JsonField = totalHours + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PayStatements = apply { - if (validated) { - return@apply - } - - earnings().ifPresent { it.validate() } - employeeDeductions().ifPresent { it.validate() } - employerContributions().ifPresent { it.validate() } - grossPay() - individualId() - netPay() - paymentMethod() - taxes().ifPresent { it.validate() } - totalHours() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [PayStatements]. + */ @JvmStatic fun builder() = Builder() } @@ -4521,6 +7649,13 @@ private constructor( fun earnings(earnings: Earnings) = earnings(JsonField.of(earnings)) + /** + * Sets [Builder.earnings] to an arbitrary JSON value. + * + * You should usually call [Builder.earnings] with a well-typed [Earnings] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun earnings(earnings: JsonField) = apply { this.earnings = earnings } @@ -4528,6 +7663,13 @@ private constructor( fun employeeDeductions(employeeDeductions: EmployeeDeductions) = employeeDeductions(JsonField.of(employeeDeductions)) + /** + * Sets [Builder.employeeDeductions] to an arbitrary JSON value. + * + * You should usually call [Builder.employeeDeductions] with a well-typed + * [EmployeeDeductions] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ fun employeeDeductions(employeeDeductions: JsonField) = apply { this.employeeDeductions = employeeDeductions @@ -4536,12 +7678,26 @@ private constructor( fun employerContributions(employerContributions: EmployerContributions) = employerContributions(JsonField.of(employerContributions)) + /** + * Sets [Builder.employerContributions] to an arbitrary JSON value. + * + * You should usually call [Builder.employerContributions] with a well-typed + * [EmployerContributions] value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ fun employerContributions( employerContributions: JsonField ) = apply { this.employerContributions = employerContributions } fun grossPay(grossPay: Boolean) = grossPay(JsonField.of(grossPay)) + /** + * Sets [Builder.grossPay] to an arbitrary JSON value. + * + * You should usually call [Builder.grossPay] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun grossPay(grossPay: JsonField) = apply { this.grossPay = grossPay } @@ -4549,33 +7705,75 @@ private constructor( fun individualId(individualId: Boolean) = individualId(JsonField.of(individualId)) + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } fun netPay(netPay: Boolean) = netPay(JsonField.of(netPay)) + /** + * Sets [Builder.netPay] to an arbitrary JSON value. + * + * You should usually call [Builder.netPay] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun netPay(netPay: JsonField) = apply { this.netPay = netPay } fun paymentMethod(paymentMethod: Boolean) = paymentMethod(JsonField.of(paymentMethod)) + /** + * Sets [Builder.paymentMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.paymentMethod] with a well-typed + * [Boolean] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun paymentMethod(paymentMethod: JsonField) = apply { this.paymentMethod = paymentMethod } fun taxes(taxes: Taxes) = taxes(JsonField.of(taxes)) + /** + * Sets [Builder.taxes] to an arbitrary JSON value. + * + * You should usually call [Builder.taxes] with a well-typed [Taxes] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun taxes(taxes: JsonField) = apply { this.taxes = taxes } fun totalHours(totalHours: Boolean) = totalHours(JsonField.of(totalHours)) + /** + * Sets [Builder.totalHours] to an arbitrary JSON value. + * + * You should usually call [Builder.totalHours] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun totalHours(totalHours: JsonField) = apply { this.totalHours = totalHours } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = @@ -4600,6 +7798,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PayStatements]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): PayStatements = PayStatements( earnings, @@ -4612,77 +7815,159 @@ private constructor( taxes, totalHours, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect - class Earnings - @JsonCreator - private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), - ) { + private var validated: Boolean = false + + fun validate(): PayStatements = apply { + if (validated) { + return@apply + } - fun amount(): Optional = - Optional.ofNullable(amount.getNullable("amount")) + earnings().ifPresent { it.validate() } + employeeDeductions().ifPresent { it.validate() } + employerContributions().ifPresent { it.validate() } + grossPay() + individualId() + netPay() + paymentMethod() + taxes().ifPresent { it.validate() } + totalHours() + type() + validated = true + } - fun currency(): Optional = - Optional.ofNullable(currency.getNullable("currency")) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } - fun name(): Optional = - Optional.ofNullable(name.getNullable("name")) + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (earnings.asKnown().getOrNull()?.validity() ?: 0) + + (employeeDeductions.asKnown().getOrNull()?.validity() ?: 0) + + (employerContributions.asKnown().getOrNull()?.validity() ?: 0) + + (if (grossPay.asKnown().isPresent) 1 else 0) + + (if (individualId.asKnown().isPresent) 1 else 0) + + (if (netPay.asKnown().isPresent) 1 else 0) + + (if (paymentMethod.asKnown().isPresent) 1 else 0) + + (taxes.asKnown().getOrNull()?.validity() ?: 0) + + (if (totalHours.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) - fun type(): Optional = - Optional.ofNullable(type.getNullable("type")) + class Earnings + private constructor( + private val amount: JsonField, + private val currency: JsonField, + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, + ) { + @JsonCreator + private constructor( + @JsonProperty("amount") + @ExcludeMissing + amount: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(amount, currency, name, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Earnings = apply { - if (validated) { - return@apply - } - - amount() - currency() - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Earnings]. + */ @JvmStatic fun builder() = Builder() } @@ -4707,20 +7992,48 @@ private constructor( fun amount(amount: Boolean) = amount(JsonField.of(amount)) + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun currency(currency: Boolean) = currency(JsonField.of(currency)) + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = @@ -4745,16 +8058,57 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Earnings]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Earnings = Earnings( amount, currency, name, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Earnings = apply { + if (validated) { + return@apply + } + + amount() + currency() + name() + type() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4773,84 +8127,129 @@ private constructor( "Earnings{amount=$amount, currency=$currency, name=$name, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class EmployeeDeductions - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("pre_tax") - @ExcludeMissing - private val preTax: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val amount: JsonField, + private val currency: JsonField, + private val name: JsonField, + private val preTax: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun amount(): Optional = - Optional.ofNullable(amount.getNullable("amount")) - - fun currency(): Optional = - Optional.ofNullable(currency.getNullable("currency")) - - fun name(): Optional = - Optional.ofNullable(name.getNullable("name")) - - fun preTax(): Optional = - Optional.ofNullable(preTax.getNullable("pre_tax")) - - fun type(): Optional = - Optional.ofNullable(type.getNullable("type")) - + @JsonCreator + private constructor( + @JsonProperty("amount") + @ExcludeMissing + amount: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("pre_tax") + @ExcludeMissing + preTax: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(amount, currency, name, preTax, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun preTax(): Optional = preTax.getOptional("pre_tax") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + /** + * Returns the raw JSON value of [preTax]. + * + * Unlike [preTax], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("pre_tax") @ExcludeMissing fun _preTax(): JsonField = preTax + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): EmployeeDeductions = apply { - if (validated) { - return@apply - } - - amount() - currency() - name() - preTax() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [EmployeeDeductions]. + */ @JvmStatic fun builder() = Builder() } @@ -4878,24 +8277,59 @@ private constructor( fun amount(amount: Boolean) = amount(JsonField.of(amount)) + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun currency(currency: Boolean) = currency(JsonField.of(currency)) + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun preTax(preTax: Boolean) = preTax(JsonField.of(preTax)) + /** + * Sets [Builder.preTax] to an arbitrary JSON value. + * + * You should usually call [Builder.preTax] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun preTax(preTax: JsonField) = apply { this.preTax = preTax } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = @@ -4920,6 +8354,12 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [EmployeeDeductions]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): EmployeeDeductions = EmployeeDeductions( amount, @@ -4927,10 +8367,47 @@ private constructor( name, preTax, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): EmployeeDeductions = apply { + if (validated) { + return@apply + } + + amount() + currency() + name() + preTax() + type() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (preTax.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -4946,67 +8423,94 @@ private constructor( override fun hashCode(): Int = hashCode override fun toString() = - "EmployeeDeductions{amount=$amount, currency=$currency, name=$name, preTax=$preTax, type=$type, additionalProperties=$additionalProperties}" - } - - @NoAutoDetect - class EmployerContributions - @JsonCreator - private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), - ) { - - fun amount(): Optional = - Optional.ofNullable(amount.getNullable("amount")) - - fun currency(): Optional = - Optional.ofNullable(currency.getNullable("currency")) + "EmployeeDeductions{amount=$amount, currency=$currency, name=$name, preTax=$preTax, type=$type, additionalProperties=$additionalProperties}" + } - fun name(): Optional = - Optional.ofNullable(name.getNullable("name")) + class EmployerContributions + private constructor( + private val amount: JsonField, + private val currency: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { + @JsonCreator + private constructor( + @JsonProperty("amount") + @ExcludeMissing + amount: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + ) : this(amount, currency, name, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): EmployerContributions = apply { - if (validated) { - return@apply - } - - amount() - currency() - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [EmployerContributions]. + */ @JvmStatic fun builder() = Builder() } @@ -5031,16 +8535,37 @@ private constructor( fun amount(amount: Boolean) = amount(JsonField.of(amount)) + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun currency(currency: Boolean) = currency(JsonField.of(currency)) + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = @@ -5065,15 +8590,54 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [EmployerContributions]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): EmployerContributions = EmployerContributions( amount, currency, name, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): EmployerContributions = apply { + if (validated) { + return@apply + } + + amount() + currency() + name() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -5092,84 +8656,128 @@ private constructor( "EmployerContributions{amount=$amount, currency=$currency, name=$name, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Taxes - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("employer") - @ExcludeMissing - private val employer: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap(), + private val amount: JsonField, + private val currency: JsonField, + private val employer: JsonField, + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun amount(): Optional = - Optional.ofNullable(amount.getNullable("amount")) - - fun currency(): Optional = - Optional.ofNullable(currency.getNullable("currency")) - - fun employer(): Optional = - Optional.ofNullable(employer.getNullable("employer")) - - fun name(): Optional = - Optional.ofNullable(name.getNullable("name")) - - fun type(): Optional = - Optional.ofNullable(type.getNullable("type")) - + @JsonCreator + private constructor( + @JsonProperty("amount") + @ExcludeMissing + amount: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("employer") + @ExcludeMissing + employer: JsonField = JsonMissing.of(), + @JsonProperty("name") + @ExcludeMissing + name: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(amount, currency, employer, name, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun employer(): Optional = employer.getOptional("employer") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency + /** + * Returns the raw JSON value of [employer]. + * + * Unlike [employer], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("employer") @ExcludeMissing fun _employer(): JsonField = employer + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Taxes = apply { - if (validated) { - return@apply - } - - amount() - currency() - employer() - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Taxes]. + */ @JvmStatic fun builder() = Builder() } @@ -5196,26 +8804,61 @@ private constructor( fun amount(amount: Boolean) = amount(JsonField.of(amount)) + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun currency(currency: Boolean) = currency(JsonField.of(currency)) + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } fun employer(employer: Boolean) = employer(JsonField.of(employer)) + /** + * Sets [Builder.employer] to an arbitrary JSON value. + * + * You should usually call [Builder.employer] with a well-typed + * [Boolean] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun employer(employer: JsonField) = apply { this.employer = employer } fun name(name: Boolean) = name(JsonField.of(name)) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun type(type: Boolean) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = @@ -5240,6 +8883,12 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Taxes]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): Taxes = Taxes( amount, @@ -5247,10 +8896,47 @@ private constructor( employer, name, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Taxes = apply { + if (validated) { + return@apply + } + + amount() + currency() + employer() + name() + type() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (employer.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (type.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -5305,158 +8991,281 @@ private constructor( "SupportedPayStatementFields{paging=$paging, payStatements=$payStatements, additionalProperties=$additionalProperties}" } - @NoAutoDetect class SupportedPaymentFields - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonProperty("company_debit") - @ExcludeMissing - private val companyDebit: JsonField = JsonMissing.of(), - @JsonProperty("debit_date") - @ExcludeMissing - private val debitDate: JsonField = JsonMissing.of(), - @JsonProperty("employee_taxes") - @ExcludeMissing - private val employeeTaxes: JsonField = JsonMissing.of(), - @JsonProperty("employer_taxes") - @ExcludeMissing - private val employerTaxes: JsonField = JsonMissing.of(), - @JsonProperty("gross_pay") - @ExcludeMissing - private val grossPay: JsonField = JsonMissing.of(), - @JsonProperty("individual_ids") - @ExcludeMissing - private val individualIds: JsonField = JsonMissing.of(), - @JsonProperty("net_pay") - @ExcludeMissing - private val netPay: JsonField = JsonMissing.of(), - @JsonProperty("pay_date") - @ExcludeMissing - private val payDate: JsonField = JsonMissing.of(), - @JsonProperty("pay_frequencies") - @ExcludeMissing - private val payFrequencies: JsonField = JsonMissing.of(), - @JsonProperty("pay_group_ids") - @ExcludeMissing - private val payGroupIds: JsonField = JsonMissing.of(), - @JsonProperty("pay_period") - @ExcludeMissing - private val payPeriod: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val companyDebit: JsonField, + private val debitDate: JsonField, + private val employeeTaxes: JsonField, + private val employerTaxes: JsonField, + private val grossPay: JsonField, + private val individualIds: JsonField, + private val netPay: JsonField, + private val payDate: JsonField, + private val payFrequencies: JsonField, + private val payGroupIds: JsonField, + private val payPeriod: JsonField, + private val additionalProperties: MutableMap, ) { - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - fun companyDebit(): Optional = - Optional.ofNullable(companyDebit.getNullable("company_debit")) - - fun debitDate(): Optional = - Optional.ofNullable(debitDate.getNullable("debit_date")) - - fun employeeTaxes(): Optional = - Optional.ofNullable(employeeTaxes.getNullable("employee_taxes")) - - fun employerTaxes(): Optional = - Optional.ofNullable(employerTaxes.getNullable("employer_taxes")) - - fun grossPay(): Optional = - Optional.ofNullable(grossPay.getNullable("gross_pay")) - - fun individualIds(): Optional = - Optional.ofNullable(individualIds.getNullable("individual_ids")) - - fun netPay(): Optional = Optional.ofNullable(netPay.getNullable("net_pay")) - - fun payDate(): Optional = - Optional.ofNullable(payDate.getNullable("pay_date")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("company_debit") + @ExcludeMissing + companyDebit: JsonField = JsonMissing.of(), + @JsonProperty("debit_date") + @ExcludeMissing + debitDate: JsonField = JsonMissing.of(), + @JsonProperty("employee_taxes") + @ExcludeMissing + employeeTaxes: JsonField = JsonMissing.of(), + @JsonProperty("employer_taxes") + @ExcludeMissing + employerTaxes: JsonField = JsonMissing.of(), + @JsonProperty("gross_pay") + @ExcludeMissing + grossPay: JsonField = JsonMissing.of(), + @JsonProperty("individual_ids") + @ExcludeMissing + individualIds: JsonField = JsonMissing.of(), + @JsonProperty("net_pay") + @ExcludeMissing + netPay: JsonField = JsonMissing.of(), + @JsonProperty("pay_date") + @ExcludeMissing + payDate: JsonField = JsonMissing.of(), + @JsonProperty("pay_frequencies") + @ExcludeMissing + payFrequencies: JsonField = JsonMissing.of(), + @JsonProperty("pay_group_ids") + @ExcludeMissing + payGroupIds: JsonField = JsonMissing.of(), + @JsonProperty("pay_period") + @ExcludeMissing + payPeriod: JsonField = JsonMissing.of(), + ) : this( + id, + companyDebit, + debitDate, + employeeTaxes, + employerTaxes, + grossPay, + individualIds, + netPay, + payDate, + payFrequencies, + payGroupIds, + payPeriod, + mutableMapOf(), + ) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun companyDebit(): Optional = companyDebit.getOptional("company_debit") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun debitDate(): Optional = debitDate.getOptional("debit_date") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun employeeTaxes(): Optional = employeeTaxes.getOptional("employee_taxes") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun employerTaxes(): Optional = employerTaxes.getOptional("employer_taxes") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun grossPay(): Optional = grossPay.getOptional("gross_pay") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun individualIds(): Optional = individualIds.getOptional("individual_ids") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun netPay(): Optional = netPay.getOptional("net_pay") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun payDate(): Optional = payDate.getOptional("pay_date") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ fun payFrequencies(): Optional = - Optional.ofNullable(payFrequencies.getNullable("pay_frequencies")) - - fun payGroupIds(): Optional = - Optional.ofNullable(payGroupIds.getNullable("pay_group_ids")) - - fun payPeriod(): Optional = - Optional.ofNullable(payPeriod.getNullable("pay_period")) - + payFrequencies.getOptional("pay_frequencies") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun payGroupIds(): Optional = payGroupIds.getOptional("pay_group_ids") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun payPeriod(): Optional = payPeriod.getOptional("pay_period") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + /** + * Returns the raw JSON value of [companyDebit]. + * + * Unlike [companyDebit], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("company_debit") @ExcludeMissing fun _companyDebit(): JsonField = companyDebit + /** + * Returns the raw JSON value of [debitDate]. + * + * Unlike [debitDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("debit_date") @ExcludeMissing fun _debitDate(): JsonField = debitDate + /** + * Returns the raw JSON value of [employeeTaxes]. + * + * Unlike [employeeTaxes], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("employee_taxes") @ExcludeMissing fun _employeeTaxes(): JsonField = employeeTaxes + /** + * Returns the raw JSON value of [employerTaxes]. + * + * Unlike [employerTaxes], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("employer_taxes") @ExcludeMissing fun _employerTaxes(): JsonField = employerTaxes + /** + * Returns the raw JSON value of [grossPay]. + * + * Unlike [grossPay], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("gross_pay") @ExcludeMissing fun _grossPay(): JsonField = grossPay + /** + * Returns the raw JSON value of [individualIds]. + * + * Unlike [individualIds], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("individual_ids") @ExcludeMissing fun _individualIds(): JsonField = individualIds + /** + * Returns the raw JSON value of [netPay]. + * + * Unlike [netPay], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("net_pay") @ExcludeMissing fun _netPay(): JsonField = netPay + /** + * Returns the raw JSON value of [payDate]. + * + * Unlike [payDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("pay_date") @ExcludeMissing fun _payDate(): JsonField = payDate + /** + * Returns the raw JSON value of [payFrequencies]. + * + * Unlike [payFrequencies], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("pay_frequencies") @ExcludeMissing fun _payFrequencies(): JsonField = payFrequencies + /** + * Returns the raw JSON value of [payGroupIds]. + * + * Unlike [payGroupIds], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("pay_group_ids") @ExcludeMissing fun _payGroupIds(): JsonField = payGroupIds + /** + * Returns the raw JSON value of [payPeriod]. + * + * Unlike [payPeriod], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("pay_period") @ExcludeMissing fun _payPeriod(): JsonField = payPeriod + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedPaymentFields = apply { - if (validated) { - return@apply - } - - id() - companyDebit() - debitDate() - employeeTaxes() - employerTaxes() - grossPay() - individualIds() - netPay() - payDate() - payFrequencies() - payGroupIds() - payPeriod().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SupportedPaymentFields]. + */ @JvmStatic fun builder() = Builder() } @@ -5497,17 +9306,38 @@ private constructor( fun id(id: Boolean) = id(JsonField.of(id)) + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun companyDebit(companyDebit: Boolean) = companyDebit(JsonField.of(companyDebit)) + /** + * Sets [Builder.companyDebit] to an arbitrary JSON value. + * + * You should usually call [Builder.companyDebit] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun companyDebit(companyDebit: JsonField) = apply { this.companyDebit = companyDebit } fun debitDate(debitDate: Boolean) = debitDate(JsonField.of(debitDate)) + /** + * Sets [Builder.debitDate] to an arbitrary JSON value. + * + * You should usually call [Builder.debitDate] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun debitDate(debitDate: JsonField) = apply { this.debitDate = debitDate } @@ -5515,6 +9345,13 @@ private constructor( fun employeeTaxes(employeeTaxes: Boolean) = employeeTaxes(JsonField.of(employeeTaxes)) + /** + * Sets [Builder.employeeTaxes] to an arbitrary JSON value. + * + * You should usually call [Builder.employeeTaxes] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun employeeTaxes(employeeTaxes: JsonField) = apply { this.employeeTaxes = employeeTaxes } @@ -5522,44 +9359,100 @@ private constructor( fun employerTaxes(employerTaxes: Boolean) = employerTaxes(JsonField.of(employerTaxes)) + /** + * Sets [Builder.employerTaxes] to an arbitrary JSON value. + * + * You should usually call [Builder.employerTaxes] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun employerTaxes(employerTaxes: JsonField) = apply { this.employerTaxes = employerTaxes } fun grossPay(grossPay: Boolean) = grossPay(JsonField.of(grossPay)) + /** + * Sets [Builder.grossPay] to an arbitrary JSON value. + * + * You should usually call [Builder.grossPay] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun grossPay(grossPay: JsonField) = apply { this.grossPay = grossPay } fun individualIds(individualIds: Boolean) = individualIds(JsonField.of(individualIds)) + /** + * Sets [Builder.individualIds] to an arbitrary JSON value. + * + * You should usually call [Builder.individualIds] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun individualIds(individualIds: JsonField) = apply { this.individualIds = individualIds } fun netPay(netPay: Boolean) = netPay(JsonField.of(netPay)) + /** + * Sets [Builder.netPay] to an arbitrary JSON value. + * + * You should usually call [Builder.netPay] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun netPay(netPay: JsonField) = apply { this.netPay = netPay } fun payDate(payDate: Boolean) = payDate(JsonField.of(payDate)) + /** + * Sets [Builder.payDate] to an arbitrary JSON value. + * + * You should usually call [Builder.payDate] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun payDate(payDate: JsonField) = apply { this.payDate = payDate } fun payFrequencies(payFrequencies: Boolean) = payFrequencies(JsonField.of(payFrequencies)) + /** + * Sets [Builder.payFrequencies] to an arbitrary JSON value. + * + * You should usually call [Builder.payFrequencies] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun payFrequencies(payFrequencies: JsonField) = apply { this.payFrequencies = payFrequencies } fun payGroupIds(payGroupIds: Boolean) = payGroupIds(JsonField.of(payGroupIds)) + /** + * Sets [Builder.payGroupIds] to an arbitrary JSON value. + * + * You should usually call [Builder.payGroupIds] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun payGroupIds(payGroupIds: JsonField) = apply { this.payGroupIds = payGroupIds } fun payPeriod(payPeriod: PayPeriod) = payPeriod(JsonField.of(payPeriod)) + /** + * Sets [Builder.payPeriod] to an arbitrary JSON value. + * + * You should usually call [Builder.payPeriod] with a well-typed [PayPeriod] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun payPeriod(payPeriod: JsonField) = apply { this.payPeriod = payPeriod } @@ -5586,6 +9479,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedPaymentFields]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedPaymentFields = SupportedPaymentFields( id, @@ -5600,58 +9498,127 @@ private constructor( payFrequencies, payGroupIds, payPeriod, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): SupportedPaymentFields = apply { + if (validated) { + return@apply + } + + id() + companyDebit() + debitDate() + employeeTaxes() + employerTaxes() + grossPay() + individualIds() + netPay() + payDate() + payFrequencies() + payGroupIds() + payPeriod().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (companyDebit.asKnown().isPresent) 1 else 0) + + (if (debitDate.asKnown().isPresent) 1 else 0) + + (if (employeeTaxes.asKnown().isPresent) 1 else 0) + + (if (employerTaxes.asKnown().isPresent) 1 else 0) + + (if (grossPay.asKnown().isPresent) 1 else 0) + + (if (individualIds.asKnown().isPresent) 1 else 0) + + (if (netPay.asKnown().isPresent) 1 else 0) + + (if (payDate.asKnown().isPresent) 1 else 0) + + (if (payFrequencies.asKnown().isPresent) 1 else 0) + + (if (payGroupIds.asKnown().isPresent) 1 else 0) + + (payPeriod.asKnown().getOrNull()?.validity() ?: 0) + class PayPeriod - @JsonCreator private constructor( - @JsonProperty("end_date") - @ExcludeMissing - private val endDate: JsonField = JsonMissing.of(), - @JsonProperty("start_date") - @ExcludeMissing - private val startDate: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val endDate: JsonField, + private val startDate: JsonField, + private val additionalProperties: MutableMap, ) { - fun endDate(): Optional = - Optional.ofNullable(endDate.getNullable("end_date")) - - fun startDate(): Optional = - Optional.ofNullable(startDate.getNullable("start_date")) - + @JsonCreator + private constructor( + @JsonProperty("end_date") + @ExcludeMissing + endDate: JsonField = JsonMissing.of(), + @JsonProperty("start_date") + @ExcludeMissing + startDate: JsonField = JsonMissing.of(), + ) : this(endDate, startDate, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun endDate(): Optional = endDate.getOptional("end_date") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). + */ + fun startDate(): Optional = startDate.getOptional("start_date") + + /** + * Returns the raw JSON value of [endDate]. + * + * Unlike [endDate], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("end_date") @ExcludeMissing fun _endDate(): JsonField = endDate + /** + * Returns the raw JSON value of [startDate]. + * + * Unlike [startDate], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("start_date") @ExcludeMissing fun _startDate(): JsonField = startDate + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PayPeriod = apply { - if (validated) { - return@apply - } - - endDate() - startDate() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [PayPeriod]. + */ @JvmStatic fun builder() = Builder() } @@ -5672,10 +9639,24 @@ private constructor( fun endDate(endDate: Boolean) = endDate(JsonField.of(endDate)) + /** + * Sets [Builder.endDate] to an arbitrary JSON value. + * + * You should usually call [Builder.endDate] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun endDate(endDate: JsonField) = apply { this.endDate = endDate } fun startDate(startDate: Boolean) = startDate(JsonField.of(startDate)) + /** + * Sets [Builder.startDate] to an arbitrary JSON value. + * + * You should usually call [Builder.startDate] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun startDate(startDate: JsonField) = apply { this.startDate = startDate } @@ -5702,10 +9683,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PayPeriod]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): PayPeriod = - PayPeriod(endDate, startDate, additionalProperties.toImmutable()) + PayPeriod(endDate, startDate, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): PayPeriod = apply { + if (validated) { + return@apply + } + + endDate() + startDate() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (endDate.asKnown().isPresent) 1 else 0) + + (if (startDate.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -5866,6 +9883,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ProviderListPage.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ProviderListPage.kt index 3d4f3975..211ce9e1 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ProviderListPage.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ProviderListPage.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.blocking.ProviderService +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull /** Return details on all available payroll and HR systems. */ class ProviderListPage @@ -65,23 +65,30 @@ private constructor( ProviderListPage(providersService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -94,6 +101,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -111,6 +126,7 @@ private constructor( companion object { + /** Returns a mutable builder for constructing an instance of [ProviderListPage]. */ @JvmStatic fun builder() = Builder() } @@ -133,7 +149,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } @@ -146,7 +167,7 @@ private constructor( while (index < page.items().size) { yield(page.items()[index++]) } - page = page.getNextPage().orElse(null) ?: break + page = page.getNextPage().getOrNull() ?: break index = 0 } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ProviderListPageAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ProviderListPageAsync.kt index 37cf24fe..d8d7a8e1 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ProviderListPageAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ProviderListPageAsync.kt @@ -10,15 +10,15 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException import com.tryfinch.api.services.async.ProviderServiceAsync +import java.util.Collections import java.util.Objects import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.function.Predicate +import kotlin.jvm.optionals.getOrNull /** Return details on all available payroll and HR systems. */ class ProviderListPageAsync @@ -71,23 +71,30 @@ private constructor( ) = ProviderListPageAsync(providersService, params, response) } - @NoAutoDetect - class Response - @JsonCreator - constructor( - @JsonProperty("items") private val items: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + class Response( + private val items: JsonField>, + private val additionalProperties: MutableMap, ) { - fun items(): List = items.getNullable("items") ?: listOf() + @JsonCreator + private constructor( + @JsonProperty("items") items: JsonField> = JsonMissing.of() + ) : this(items, mutableMapOf()) + + fun items(): List = items.getOptional("items").getOrNull() ?: listOf() @JsonProperty("items") fun _items(): Optional>> = Optional.ofNullable(items) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) private var validated: Boolean = false @@ -100,6 +107,14 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { @@ -117,6 +132,9 @@ private constructor( companion object { + /** + * Returns a mutable builder for constructing an instance of [ProviderListPageAsync]. + */ @JvmStatic fun builder() = Builder() } @@ -139,7 +157,12 @@ private constructor( this.additionalProperties.put(key, value) } - fun build() = Response(items, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Response]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Response = Response(items, additionalProperties.toMutableMap()) } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ProviderListParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ProviderListParams.kt index 2940b01d..dbf39fca 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ProviderListParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/ProviderListParams.kt @@ -2,7 +2,6 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams @@ -19,21 +18,17 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): ProviderListParams = builder().build() + /** Returns a mutable builder for constructing an instance of [ProviderListParams]. */ @JvmStatic fun builder() = Builder() } /** A builder for [ProviderListParams]. */ - @NoAutoDetect class Builder internal constructor() { private var additionalHeaders: Headers.Builder = Headers.builder() @@ -143,10 +138,19 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [ProviderListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ProviderListParams = ProviderListParams(additionalHeaders.build(), additionalQueryParams.build()) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RequestForwardingForwardParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RequestForwardingForwardParams.kt index 7379952c..b66c89fe 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RequestForwardingForwardParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RequestForwardingForwardParams.kt @@ -10,15 +10,15 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** * The Forward API allows you to make direct requests to an employment system. If Finch’s unified @@ -35,18 +35,27 @@ private constructor( /** * The HTTP method for the forwarded request. Valid values include: `GET` , `POST` , `PUT` , * `DELETE` , and `PATCH`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ fun method(): String = body.method() /** * The URL route path for the forwarded request. This value must begin with a forward-slash ( / * ) and may only contain alphanumeric characters, hyphens, and underscores. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ fun route(): String = body.route() /** * The body for the forwarded request. This value must be specified as either a string or a * valid JSON object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ fun data(): Optional = body.data() @@ -64,20 +73,23 @@ private constructor( fun _params(): JsonValue = body._params() /** - * The HTTP method for the forwarded request. Valid values include: `GET` , `POST` , `PUT` , - * `DELETE` , and `PATCH`. + * Returns the raw JSON value of [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. */ fun _method(): JsonField = body._method() /** - * The URL route path for the forwarded request. This value must begin with a forward-slash ( / - * ) and may only contain alphanumeric characters, hyphens, and underscores. + * Returns the raw JSON value of [route]. + * + * Unlike [route], this method doesn't throw if the JSON field has an unexpected type. */ fun _route(): JsonField = body._route() /** - * The body for the forwarded request. This value must be specified as either a string or a - * valid JSON object. + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. */ fun _data(): JsonField = body._data() @@ -87,239 +99,24 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - /** Forward Request Body */ - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("route") - @ExcludeMissing - private val route: JsonField = JsonMissing.of(), - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("headers") @ExcludeMissing private val headers: JsonValue = JsonMissing.of(), - @JsonProperty("params") @ExcludeMissing private val params: JsonValue = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** - * The HTTP method for the forwarded request. Valid values include: `GET` , `POST` , `PUT` , - * `DELETE` , and `PATCH`. - */ - fun method(): String = method.getRequired("method") - - /** - * The URL route path for the forwarded request. This value must begin with a forward-slash - * ( / ) and may only contain alphanumeric characters, hyphens, and underscores. - */ - fun route(): String = route.getRequired("route") - - /** - * The body for the forwarded request. This value must be specified as either a string or a - * valid JSON object. - */ - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) - - /** - * The HTTP headers to include on the forwarded request. This value must be specified as an - * object of key-value pairs. Example: `{"Content-Type": "application/xml", "X-API-Version": - * "v1" }` - */ - @JsonProperty("headers") @ExcludeMissing fun _headers_(): JsonValue = headers - - /** - * The query parameters for the forwarded request. This value must be specified as a valid - * JSON object rather than a query string. - */ - @JsonProperty("params") @ExcludeMissing fun _params(): JsonValue = params - - /** - * The HTTP method for the forwarded request. Valid values include: `GET` , `POST` , `PUT` , - * `DELETE` , and `PATCH`. - */ - @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method - - /** - * The URL route path for the forwarded request. This value must begin with a forward-slash - * ( / ) and may only contain alphanumeric characters, hyphens, and underscores. - */ - @JsonProperty("route") @ExcludeMissing fun _route(): JsonField = route - - /** - * The body for the forwarded request. This value must be specified as either a string or a - * valid JSON object. - */ - @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - method() - route() - data() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var method: JsonField? = null - private var route: JsonField? = null - private var data: JsonField = JsonMissing.of() - private var headers: JsonValue = JsonMissing.of() - private var params: JsonValue = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - method = body.method - route = body.route - data = body.data - headers = body.headers - params = body.params - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** - * The HTTP method for the forwarded request. Valid values include: `GET` , `POST` , - * `PUT` , `DELETE` , and `PATCH`. - */ - fun method(method: String) = method(JsonField.of(method)) - - /** - * The HTTP method for the forwarded request. Valid values include: `GET` , `POST` , - * `PUT` , `DELETE` , and `PATCH`. - */ - fun method(method: JsonField) = apply { this.method = method } - - /** - * The URL route path for the forwarded request. This value must begin with a - * forward-slash ( / ) and may only contain alphanumeric characters, hyphens, and - * underscores. - */ - fun route(route: String) = route(JsonField.of(route)) - - /** - * The URL route path for the forwarded request. This value must begin with a - * forward-slash ( / ) and may only contain alphanumeric characters, hyphens, and - * underscores. - */ - fun route(route: JsonField) = apply { this.route = route } - - /** - * The body for the forwarded request. This value must be specified as either a string - * or a valid JSON object. - */ - fun data(data: String?) = data(JsonField.ofNullable(data)) - - /** - * The body for the forwarded request. This value must be specified as either a string - * or a valid JSON object. - */ - fun data(data: Optional) = data(data.orElse(null)) - - /** - * The body for the forwarded request. This value must be specified as either a string - * or a valid JSON object. - */ - fun data(data: JsonField) = apply { this.data = data } - - /** - * The HTTP headers to include on the forwarded request. This value must be specified as - * an object of key-value pairs. Example: `{"Content-Type": "application/xml", - * "X-API-Version": "v1" }` - */ - fun headers(headers: JsonValue) = apply { this.headers = headers } - - /** - * The query parameters for the forwarded request. This value must be specified as a - * valid JSON object rather than a query string. - */ - fun params(params: JsonValue) = apply { this.params = params } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = - Body( - checkRequired("method", method), - checkRequired("route", route), - data, - headers, - params, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && method == other.method && route == other.route && data == other.data && headers == other.headers && params == other.params && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(method, route, data, headers, params, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{method=$method, route=$route, data=$data, headers=$headers, params=$params, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [RequestForwardingForwardParams]. + * + * The following fields are required: + * ```java + * .method() + * .route() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [RequestForwardingForwardParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -333,6 +130,20 @@ private constructor( additionalQueryParams = requestForwardingForwardParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [method] + * - [route] + * - [data] + * - [headers] + * - [params] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** * The HTTP method for the forwarded request. Valid values include: `GET` , `POST` , `PUT` , * `DELETE` , and `PATCH`. @@ -340,8 +151,10 @@ private constructor( fun method(method: String) = apply { body.method(method) } /** - * The HTTP method for the forwarded request. Valid values include: `GET` , `POST` , `PUT` , - * `DELETE` , and `PATCH`. + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun method(method: JsonField) = apply { body.method(method) } @@ -352,8 +165,10 @@ private constructor( fun route(route: String) = apply { body.route(route) } /** - * The URL route path for the forwarded request. This value must begin with a forward-slash - * ( / ) and may only contain alphanumeric characters, hyphens, and underscores. + * Sets [Builder.route] to an arbitrary JSON value. + * + * You should usually call [Builder.route] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun route(route: JsonField) = apply { body.route(route) } @@ -363,15 +178,14 @@ private constructor( */ fun data(data: String?) = apply { body.data(data) } - /** - * The body for the forwarded request. This value must be specified as either a string or a - * valid JSON object. - */ - fun data(data: Optional) = data(data.orElse(null)) + /** Alias for calling [Builder.data] with `data.orElse(null)`. */ + fun data(data: Optional) = data(data.getOrNull()) /** - * The body for the forwarded request. This value must be specified as either a string or a - * valid JSON object. + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun data(data: JsonField) = apply { body.data(data) } @@ -505,6 +319,19 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [RequestForwardingForwardParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .method() + * .route() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): RequestForwardingForwardParams = RequestForwardingForwardParams( body.build(), @@ -513,6 +340,295 @@ private constructor( ) } + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + /** Forward Request Body */ + class Body + private constructor( + private val method: JsonField, + private val route: JsonField, + private val data: JsonField, + private val headers: JsonValue, + private val params: JsonValue, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("method") @ExcludeMissing method: JsonField = JsonMissing.of(), + @JsonProperty("route") @ExcludeMissing route: JsonField = JsonMissing.of(), + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("headers") @ExcludeMissing headers: JsonValue = JsonMissing.of(), + @JsonProperty("params") @ExcludeMissing params: JsonValue = JsonMissing.of(), + ) : this(method, route, data, headers, params, mutableMapOf()) + + /** + * The HTTP method for the forwarded request. Valid values include: `GET` , `POST` , `PUT` , + * `DELETE` , and `PATCH`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun method(): String = method.getRequired("method") + + /** + * The URL route path for the forwarded request. This value must begin with a forward-slash + * ( / ) and may only contain alphanumeric characters, hyphens, and underscores. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun route(): String = route.getRequired("route") + + /** + * The body for the forwarded request. This value must be specified as either a string or a + * valid JSON object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") + + /** + * The HTTP headers to include on the forwarded request. This value must be specified as an + * object of key-value pairs. Example: `{"Content-Type": "application/xml", "X-API-Version": + * "v1" }` + */ + @JsonProperty("headers") @ExcludeMissing fun _headers_(): JsonValue = headers + + /** + * The query parameters for the forwarded request. This value must be specified as a valid + * JSON object rather than a query string. + */ + @JsonProperty("params") @ExcludeMissing fun _params(): JsonValue = params + + /** + * Returns the raw JSON value of [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method + + /** + * Returns the raw JSON value of [route]. + * + * Unlike [route], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("route") @ExcludeMissing fun _route(): JsonField = route + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .method() + * .route() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var method: JsonField? = null + private var route: JsonField? = null + private var data: JsonField = JsonMissing.of() + private var headers: JsonValue = JsonMissing.of() + private var params: JsonValue = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + method = body.method + route = body.route + data = body.data + headers = body.headers + params = body.params + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** + * The HTTP method for the forwarded request. Valid values include: `GET` , `POST` , + * `PUT` , `DELETE` , and `PATCH`. + */ + fun method(method: String) = method(JsonField.of(method)) + + /** + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun method(method: JsonField) = apply { this.method = method } + + /** + * The URL route path for the forwarded request. This value must begin with a + * forward-slash ( / ) and may only contain alphanumeric characters, hyphens, and + * underscores. + */ + fun route(route: String) = route(JsonField.of(route)) + + /** + * Sets [Builder.route] to an arbitrary JSON value. + * + * You should usually call [Builder.route] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun route(route: JsonField) = apply { this.route = route } + + /** + * The body for the forwarded request. This value must be specified as either a string + * or a valid JSON object. + */ + fun data(data: String?) = data(JsonField.ofNullable(data)) + + /** Alias for calling [Builder.data] with `data.orElse(null)`. */ + fun data(data: Optional) = data(data.getOrNull()) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun data(data: JsonField) = apply { this.data = data } + + /** + * The HTTP headers to include on the forwarded request. This value must be specified as + * an object of key-value pairs. Example: `{"Content-Type": "application/xml", + * "X-API-Version": "v1" }` + */ + fun headers(headers: JsonValue) = apply { this.headers = headers } + + /** + * The query parameters for the forwarded request. This value must be specified as a + * valid JSON object rather than a query string. + */ + fun params(params: JsonValue) = apply { this.params = params } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .method() + * .route() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("method", method), + checkRequired("route", route), + data, + headers, + params, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + method() + route() + data() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (method.asKnown().isPresent) 1 else 0) + + (if (route.asKnown().isPresent) 1 else 0) + + (if (data.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && method == other.method && route == other.route && data == other.data && headers == other.headers && params == other.params && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(method, route, data, headers, params, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{method=$method, route=$route, data=$data, headers=$headers, params=$params, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RequestForwardingForwardResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RequestForwardingForwardResponse.kt index 3a8cbd7e..975d9d29 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RequestForwardingForwardResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RequestForwardingForwardResponse.kt @@ -10,34 +10,39 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class RequestForwardingForwardResponse -@JsonCreator private constructor( - @JsonProperty("data") @ExcludeMissing private val data: JsonField = JsonMissing.of(), - @JsonProperty("headers") @ExcludeMissing private val headers: JsonValue = JsonMissing.of(), - @JsonProperty("request") - @ExcludeMissing - private val request: JsonField = JsonMissing.of(), - @JsonProperty("statusCode") - @ExcludeMissing - private val statusCode: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val headers: JsonValue, + private val request: JsonField, + private val statusCode: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("headers") @ExcludeMissing headers: JsonValue = JsonMissing.of(), + @JsonProperty("request") @ExcludeMissing request: JsonField = JsonMissing.of(), + @JsonProperty("statusCode") @ExcludeMissing statusCode: JsonField = JsonMissing.of(), + ) : this(data, headers, request, statusCode, mutableMapOf()) + /** * A string representation of the HTTP response body of the forwarded request’s response * received from the underlying integration’s API. This field may be null in the case where the * upstream system’s response is empty. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + fun data(): Optional = data.getOptional("data") /** * The HTTP headers of the forwarded request’s response, exactly as received from the underlying @@ -47,54 +52,68 @@ private constructor( /** * An object containing details of your original forwarded request, for your ease of reference. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ fun request(): Request = request.getRequired("request") /** * The HTTP status code of the forwarded request’s response, exactly received from the * underlying integration’s API. This value will be returned as an integer. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). */ fun statusCode(): Long = statusCode.getRequired("statusCode") /** - * A string representation of the HTTP response body of the forwarded request’s response - * received from the underlying integration’s API. This field may be null in the case where the - * upstream system’s response is empty. + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data /** - * An object containing details of your original forwarded request, for your ease of reference. + * Returns the raw JSON value of [request]. + * + * Unlike [request], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("request") @ExcludeMissing fun _request(): JsonField = request /** - * The HTTP status code of the forwarded request’s response, exactly received from the - * underlying integration’s API. This value will be returned as an integer. + * Returns the raw JSON value of [statusCode]. + * + * Unlike [statusCode], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("statusCode") @ExcludeMissing fun _statusCode(): JsonField = statusCode + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): RequestForwardingForwardResponse = apply { - if (validated) { - return@apply - } - - data() - request().validate() - statusCode() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [RequestForwardingForwardResponse]. + * + * The following fields are required: + * ```java + * .data() + * .headers() + * .request() + * .statusCode() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -125,17 +144,14 @@ private constructor( */ fun data(data: String?) = data(JsonField.ofNullable(data)) - /** - * A string representation of the HTTP response body of the forwarded request’s response - * received from the underlying integration’s API. This field may be null in the case where - * the upstream system’s response is empty. - */ - fun data(data: Optional) = data(data.orElse(null)) + /** Alias for calling [Builder.data] with `data.orElse(null)`. */ + fun data(data: Optional) = data(data.getOrNull()) /** - * A string representation of the HTTP response body of the forwarded request’s response - * received from the underlying integration’s API. This field may be null in the case where - * the upstream system’s response is empty. + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun data(data: JsonField) = apply { this.data = data } @@ -152,8 +168,10 @@ private constructor( fun request(request: Request) = request(JsonField.of(request)) /** - * An object containing details of your original forwarded request, for your ease of - * reference. + * Sets [Builder.request] to an arbitrary JSON value. + * + * You should usually call [Builder.request] with a well-typed [Request] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun request(request: JsonField) = apply { this.request = request } @@ -164,8 +182,10 @@ private constructor( fun statusCode(statusCode: Long) = statusCode(JsonField.of(statusCode)) /** - * The HTTP status code of the forwarded request’s response, exactly received from the - * underlying integration’s API. This value will be returned as an integer. + * Sets [Builder.statusCode] to an arbitrary JSON value. + * + * You should usually call [Builder.statusCode] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun statusCode(statusCode: JsonField) = apply { this.statusCode = statusCode } @@ -188,44 +208,94 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [RequestForwardingForwardResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .data() + * .headers() + * .request() + * .statusCode() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): RequestForwardingForwardResponse = RequestForwardingForwardResponse( checkRequired("data", data), checkRequired("headers", headers), checkRequired("request", request), checkRequired("statusCode", statusCode), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): RequestForwardingForwardResponse = apply { + if (validated) { + return@apply + } + + data() + request().validate() + statusCode() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + + (request.asKnown().getOrNull()?.validity() ?: 0) + + (if (statusCode.asKnown().isPresent) 1 else 0) + /** * An object containing details of your original forwarded request, for your ease of reference. */ - @NoAutoDetect class Request - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("headers") @ExcludeMissing private val headers: JsonValue = JsonMissing.of(), - @JsonProperty("method") - @ExcludeMissing - private val method: JsonField = JsonMissing.of(), - @JsonProperty("params") @ExcludeMissing private val params: JsonValue = JsonMissing.of(), - @JsonProperty("route") - @ExcludeMissing - private val route: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val headers: JsonValue, + private val method: JsonField, + private val params: JsonValue, + private val route: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("headers") @ExcludeMissing headers: JsonValue = JsonMissing.of(), + @JsonProperty("method") @ExcludeMissing method: JsonField = JsonMissing.of(), + @JsonProperty("params") @ExcludeMissing params: JsonValue = JsonMissing.of(), + @JsonProperty("route") @ExcludeMissing route: JsonField = JsonMissing.of(), + ) : this(data, headers, method, params, route, mutableMapOf()) + /** * The body that was specified for the forwarded request. If a value was not specified in * the original request, this value will be returned as null ; otherwise, this value will * always be returned as a string. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + fun data(): Optional = data.getOptional("data") /** * The specified HTTP headers that were included in the forwarded request. If no headers @@ -236,6 +306,9 @@ private constructor( /** * The HTTP method that was specified for the forwarded request. Valid values include: `GET` * , `POST` , `PUT` , `DELETE` , and `PATCH`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). */ fun method(): String = method.getRequired("method") @@ -245,46 +318,61 @@ private constructor( */ @JsonProperty("params") @ExcludeMissing fun _params(): JsonValue = params - /** The URL route path that was specified for the forwarded request. */ + /** + * The URL route path that was specified for the forwarded request. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ fun route(): String = route.getRequired("route") /** - * The body that was specified for the forwarded request. If a value was not specified in - * the original request, this value will be returned as null ; otherwise, this value will - * always be returned as a string. + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data /** - * The HTTP method that was specified for the forwarded request. Valid values include: `GET` - * , `POST` , `PUT` , `DELETE` , and `PATCH`. + * Returns the raw JSON value of [method]. + * + * Unlike [method], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("method") @ExcludeMissing fun _method(): JsonField = method - /** The URL route path that was specified for the forwarded request. */ + /** + * Returns the raw JSON value of [route]. + * + * Unlike [route], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("route") @ExcludeMissing fun _route(): JsonField = route + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Request = apply { - if (validated) { - return@apply - } - - data() - method() - route() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Request]. + * + * The following fields are required: + * ```java + * .data() + * .headers() + * .method() + * .params() + * .route() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -315,17 +403,15 @@ private constructor( */ fun data(data: String?) = data(JsonField.ofNullable(data)) - /** - * The body that was specified for the forwarded request. If a value was not specified - * in the original request, this value will be returned as null ; otherwise, this value - * will always be returned as a string. - */ - fun data(data: Optional) = data(data.orElse(null)) + /** Alias for calling [Builder.data] with `data.orElse(null)`. */ + fun data(data: Optional) = data(data.getOrNull()) /** - * The body that was specified for the forwarded request. If a value was not specified - * in the original request, this value will be returned as null ; otherwise, this value - * will always be returned as a string. + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. */ fun data(data: JsonField) = apply { this.data = data } @@ -342,8 +428,11 @@ private constructor( fun method(method: String) = method(JsonField.of(method)) /** - * The HTTP method that was specified for the forwarded request. Valid values include: - * `GET` , `POST` , `PUT` , `DELETE` , and `PATCH`. + * Sets [Builder.method] to an arbitrary JSON value. + * + * You should usually call [Builder.method] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun method(method: JsonField) = apply { this.method = method } @@ -356,7 +445,13 @@ private constructor( /** The URL route path that was specified for the forwarded request. */ fun route(route: String) = route(JsonField.of(route)) - /** The URL route path that was specified for the forwarded request. */ + /** + * Sets [Builder.route] to an arbitrary JSON value. + * + * You should usually call [Builder.route] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun route(route: JsonField) = apply { this.route = route } fun additionalProperties(additionalProperties: Map) = apply { @@ -378,6 +473,22 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Request]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .data() + * .headers() + * .method() + * .params() + * .route() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Request = Request( checkRequired("data", data), @@ -385,10 +496,43 @@ private constructor( checkRequired("method", method), checkRequired("params", params), checkRequired("route", route), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Request = apply { + if (validated) { + return@apply + } + + data() + method() + route() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + + (if (method.asKnown().isPresent) 1 else 0) + + (if (route.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RuleCreateResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RuleCreateResponse.kt new file mode 100644 index 00000000..c2326d4a --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RuleCreateResponse.kt @@ -0,0 +1,1218 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.tryfinch.api.core.Enum +import com.tryfinch.api.core.ExcludeMissing +import com.tryfinch.api.core.JsonField +import com.tryfinch.api.core.JsonMissing +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.checkKnown +import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class RuleCreateResponse +private constructor( + private val id: JsonField, + private val attributes: JsonField, + private val conditions: JsonField>, + private val createdAt: JsonField, + private val effectiveEndDate: JsonField, + private val effectiveStartDate: JsonField, + private val entityType: JsonField, + private val priority: JsonField, + private val updatedAt: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("conditions") + @ExcludeMissing + conditions: JsonField> = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("effective_end_date") + @ExcludeMissing + effectiveEndDate: JsonField = JsonMissing.of(), + @JsonProperty("effective_start_date") + @ExcludeMissing + effectiveStartDate: JsonField = JsonMissing.of(), + @JsonProperty("entity_type") + @ExcludeMissing + entityType: JsonField = JsonMissing.of(), + @JsonProperty("priority") @ExcludeMissing priority: JsonField = JsonMissing.of(), + @JsonProperty("updated_at") + @ExcludeMissing + updatedAt: JsonField = JsonMissing.of(), + ) : this( + id, + attributes, + conditions, + createdAt, + effectiveEndDate, + effectiveStartDate, + entityType, + priority, + updatedAt, + mutableMapOf(), + ) + + /** + * Finch id (uuidv4) for the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Specifies the fields to be applied when the condition is met. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun conditions(): Optional> = conditions.getOptional("conditions") + + /** + * The datetime when the rule was created. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun createdAt(): Optional = createdAt.getOptional("created_at") + + /** + * Specifies when the rules should stop applying rules based on the date. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun effectiveEndDate(): Optional = effectiveEndDate.getOptional("effective_end_date") + + /** + * Specifies when the rule should begin applying based on the date. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun effectiveStartDate(): Optional = + effectiveStartDate.getOptional("effective_start_date") + + /** + * The entity type to which the rule is applied. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun entityType(): Optional = entityType.getOptional("entity_type") + + /** + * The priority of the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun priority(): Optional = priority.getOptional("priority") + + /** + * The datetime when the rule was last updated. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("attributes") + @ExcludeMissing + fun _attributes(): JsonField = attributes + + /** + * Returns the raw JSON value of [conditions]. + * + * Unlike [conditions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("conditions") + @ExcludeMissing + fun _conditions(): JsonField> = conditions + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [effectiveEndDate]. + * + * Unlike [effectiveEndDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("effective_end_date") + @ExcludeMissing + fun _effectiveEndDate(): JsonField = effectiveEndDate + + /** + * Returns the raw JSON value of [effectiveStartDate]. + * + * Unlike [effectiveStartDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("effective_start_date") + @ExcludeMissing + fun _effectiveStartDate(): JsonField = effectiveStartDate + + /** + * Returns the raw JSON value of [entityType]. + * + * Unlike [entityType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("entity_type") + @ExcludeMissing + fun _entityType(): JsonField = entityType + + /** + * Returns the raw JSON value of [priority]. + * + * Unlike [priority], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("priority") @ExcludeMissing fun _priority(): JsonField = priority + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("updated_at") + @ExcludeMissing + fun _updatedAt(): JsonField = updatedAt + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [RuleCreateResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RuleCreateResponse]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var attributes: JsonField = JsonMissing.of() + private var conditions: JsonField>? = null + private var createdAt: JsonField = JsonMissing.of() + private var effectiveEndDate: JsonField = JsonMissing.of() + private var effectiveStartDate: JsonField = JsonMissing.of() + private var entityType: JsonField = JsonMissing.of() + private var priority: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(ruleCreateResponse: RuleCreateResponse) = apply { + id = ruleCreateResponse.id + attributes = ruleCreateResponse.attributes + conditions = ruleCreateResponse.conditions.map { it.toMutableList() } + createdAt = ruleCreateResponse.createdAt + effectiveEndDate = ruleCreateResponse.effectiveEndDate + effectiveStartDate = ruleCreateResponse.effectiveStartDate + entityType = ruleCreateResponse.entityType + priority = ruleCreateResponse.priority + updatedAt = ruleCreateResponse.updatedAt + additionalProperties = ruleCreateResponse.additionalProperties.toMutableMap() + } + + /** Finch id (uuidv4) for the rule. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Specifies the fields to be applied when the condition is met. */ + fun attributes(attributes: Attributes) = attributes(JsonField.of(attributes)) + + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun attributes(attributes: JsonField) = apply { this.attributes = attributes } + + fun conditions(conditions: List) = conditions(JsonField.of(conditions)) + + /** + * Sets [Builder.conditions] to an arbitrary JSON value. + * + * You should usually call [Builder.conditions] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun conditions(conditions: JsonField>) = apply { + this.conditions = conditions.map { it.toMutableList() } + } + + /** + * Adds a single [Condition] to [conditions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addCondition(condition: Condition) = apply { + conditions = + (conditions ?: JsonField.of(mutableListOf())).also { + checkKnown("conditions", it).add(condition) + } + } + + /** The datetime when the rule was created. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + /** Specifies when the rules should stop applying rules based on the date. */ + fun effectiveEndDate(effectiveEndDate: String?) = + effectiveEndDate(JsonField.ofNullable(effectiveEndDate)) + + /** Alias for calling [Builder.effectiveEndDate] with `effectiveEndDate.orElse(null)`. */ + fun effectiveEndDate(effectiveEndDate: Optional) = + effectiveEndDate(effectiveEndDate.getOrNull()) + + /** + * Sets [Builder.effectiveEndDate] to an arbitrary JSON value. + * + * You should usually call [Builder.effectiveEndDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun effectiveEndDate(effectiveEndDate: JsonField) = apply { + this.effectiveEndDate = effectiveEndDate + } + + /** Specifies when the rule should begin applying based on the date. */ + fun effectiveStartDate(effectiveStartDate: String?) = + effectiveStartDate(JsonField.ofNullable(effectiveStartDate)) + + /** + * Alias for calling [Builder.effectiveStartDate] with `effectiveStartDate.orElse(null)`. + */ + fun effectiveStartDate(effectiveStartDate: Optional) = + effectiveStartDate(effectiveStartDate.getOrNull()) + + /** + * Sets [Builder.effectiveStartDate] to an arbitrary JSON value. + * + * You should usually call [Builder.effectiveStartDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun effectiveStartDate(effectiveStartDate: JsonField) = apply { + this.effectiveStartDate = effectiveStartDate + } + + /** The entity type to which the rule is applied. */ + fun entityType(entityType: EntityType) = entityType(JsonField.of(entityType)) + + /** + * Sets [Builder.entityType] to an arbitrary JSON value. + * + * You should usually call [Builder.entityType] with a well-typed [EntityType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun entityType(entityType: JsonField) = apply { this.entityType = entityType } + + /** The priority of the rule. */ + fun priority(priority: Long) = priority(JsonField.of(priority)) + + /** + * Sets [Builder.priority] to an arbitrary JSON value. + * + * You should usually call [Builder.priority] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun priority(priority: JsonField) = apply { this.priority = priority } + + /** The datetime when the rule was last updated. */ + fun updatedAt(updatedAt: OffsetDateTime) = updatedAt(JsonField.of(updatedAt)) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun updatedAt(updatedAt: JsonField) = apply { this.updatedAt = updatedAt } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RuleCreateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RuleCreateResponse = + RuleCreateResponse( + id, + attributes, + (conditions ?: JsonMissing.of()).map { it.toImmutable() }, + createdAt, + effectiveEndDate, + effectiveStartDate, + entityType, + priority, + updatedAt, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): RuleCreateResponse = apply { + if (validated) { + return@apply + } + + id() + attributes().ifPresent { it.validate() } + conditions().ifPresent { it.forEach { it.validate() } } + createdAt() + effectiveEndDate() + effectiveStartDate() + entityType().ifPresent { it.validate() } + priority() + updatedAt() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (conditions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (effectiveEndDate.asKnown().isPresent) 1 else 0) + + (if (effectiveStartDate.asKnown().isPresent) 1 else 0) + + (entityType.asKnown().getOrNull()?.validity() ?: 0) + + (if (priority.asKnown().isPresent) 1 else 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + /** Specifies the fields to be applied when the condition is met. */ + class Attributes + private constructor( + private val metadata: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values can + * be of any type (string, number, boolean, object, array, etc.). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Attributes]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Attributes]. */ + class Builder internal constructor() { + + private var metadata: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(attributes: Attributes) = apply { + metadata = attributes.metadata + additionalProperties = attributes.additionalProperties.toMutableMap() + } + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values + * can be of any type (string, number, boolean, object, array, etc.). + */ + fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Attributes = Attributes(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values can + * be of any type (string, number, boolean, object, array, etc.). + */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Metadata && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Attributes && metadata == other.metadata && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(metadata, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Attributes{metadata=$metadata, additionalProperties=$additionalProperties}" + } + + class Condition + private constructor( + private val field: JsonField, + private val operator: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("field") @ExcludeMissing field: JsonField = JsonMissing.of(), + @JsonProperty("operator") + @ExcludeMissing + operator: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + ) : this(field, operator, value, mutableMapOf()) + + /** + * The field to be checked in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun field(): Optional = field.getOptional("field") + + /** + * The operator to be used in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun operator(): Optional = operator.getOptional("operator") + + /** + * The value of the field to be checked in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun value(): Optional = value.getOptional("value") + + /** + * Returns the raw JSON value of [field]. + * + * Unlike [field], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("field") @ExcludeMissing fun _field(): JsonField = field + + /** + * Returns the raw JSON value of [operator]. + * + * Unlike [operator], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("operator") @ExcludeMissing fun _operator(): JsonField = operator + + /** + * Returns the raw JSON value of [value]. + * + * Unlike [value], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Condition]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Condition]. */ + class Builder internal constructor() { + + private var field: JsonField = JsonMissing.of() + private var operator: JsonField = JsonMissing.of() + private var value: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(condition: Condition) = apply { + field = condition.field + operator = condition.operator + value = condition.value + additionalProperties = condition.additionalProperties.toMutableMap() + } + + /** The field to be checked in the rule. */ + fun field(field: String) = field(JsonField.of(field)) + + /** + * Sets [Builder.field] to an arbitrary JSON value. + * + * You should usually call [Builder.field] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun field(field: JsonField) = apply { this.field = field } + + /** The operator to be used in the rule. */ + fun operator(operator: Operator) = operator(JsonField.of(operator)) + + /** + * Sets [Builder.operator] to an arbitrary JSON value. + * + * You should usually call [Builder.operator] with a well-typed [Operator] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun operator(operator: JsonField) = apply { this.operator = operator } + + /** The value of the field to be checked in the rule. */ + fun value(value: String) = value(JsonField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary JSON value. + * + * You should usually call [Builder.value] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun value(value: JsonField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Condition]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Condition = + Condition(field, operator, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Condition = apply { + if (validated) { + return@apply + } + + field() + operator().ifPresent { it.validate() } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (field.asKnown().isPresent) 1 else 0) + + (operator.asKnown().getOrNull()?.validity() ?: 0) + + (if (value.asKnown().isPresent) 1 else 0) + + /** The operator to be used in the rule. */ + class Operator @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val EQUALS = of("equals") + + @JvmStatic fun of(value: String) = Operator(JsonField.of(value)) + } + + /** An enum containing [Operator]'s known values. */ + enum class Known { + EQUALS + } + + /** + * An enum containing [Operator]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Operator] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + EQUALS, + /** + * An enum member indicating that [Operator] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + EQUALS -> Value.EQUALS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws FinchInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + EQUALS -> Known.EQUALS + else -> throw FinchInvalidDataException("Unknown Operator: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws FinchInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + FinchInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Operator = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Operator && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Condition && field == other.field && operator == other.operator && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(field, operator, value, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Condition{field=$field, operator=$operator, value=$value, additionalProperties=$additionalProperties}" + } + + /** The entity type to which the rule is applied. */ + class EntityType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PAY_STATEMENT_ITEM = of("pay_statement_item") + + @JvmStatic fun of(value: String) = EntityType(JsonField.of(value)) + } + + /** An enum containing [EntityType]'s known values. */ + enum class Known { + PAY_STATEMENT_ITEM + } + + /** + * An enum containing [EntityType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [EntityType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PAY_STATEMENT_ITEM, + /** + * An enum member indicating that [EntityType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PAY_STATEMENT_ITEM -> Value.PAY_STATEMENT_ITEM + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws FinchInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + PAY_STATEMENT_ITEM -> Known.PAY_STATEMENT_ITEM + else -> throw FinchInvalidDataException("Unknown EntityType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws FinchInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): EntityType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is EntityType && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is RuleCreateResponse && id == other.id && attributes == other.attributes && conditions == other.conditions && createdAt == other.createdAt && effectiveEndDate == other.effectiveEndDate && effectiveStartDate == other.effectiveStartDate && entityType == other.entityType && priority == other.priority && updatedAt == other.updatedAt && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(id, attributes, conditions, createdAt, effectiveEndDate, effectiveStartDate, entityType, priority, updatedAt, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RuleCreateResponse{id=$id, attributes=$attributes, conditions=$conditions, createdAt=$createdAt, effectiveEndDate=$effectiveEndDate, effectiveStartDate=$effectiveStartDate, entityType=$entityType, priority=$priority, updatedAt=$updatedAt, additionalProperties=$additionalProperties}" +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RuleDeleteResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RuleDeleteResponse.kt new file mode 100644 index 00000000..00f8fca9 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RuleDeleteResponse.kt @@ -0,0 +1,1257 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.tryfinch.api.core.Enum +import com.tryfinch.api.core.ExcludeMissing +import com.tryfinch.api.core.JsonField +import com.tryfinch.api.core.JsonMissing +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.checkKnown +import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class RuleDeleteResponse +private constructor( + private val id: JsonField, + private val attributes: JsonField, + private val conditions: JsonField>, + private val createdAt: JsonField, + private val deletedAt: JsonField, + private val effectiveEndDate: JsonField, + private val effectiveStartDate: JsonField, + private val entityType: JsonField, + private val priority: JsonField, + private val updatedAt: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("conditions") + @ExcludeMissing + conditions: JsonField> = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("deleted_at") + @ExcludeMissing + deletedAt: JsonField = JsonMissing.of(), + @JsonProperty("effective_end_date") + @ExcludeMissing + effectiveEndDate: JsonField = JsonMissing.of(), + @JsonProperty("effective_start_date") + @ExcludeMissing + effectiveStartDate: JsonField = JsonMissing.of(), + @JsonProperty("entity_type") + @ExcludeMissing + entityType: JsonField = JsonMissing.of(), + @JsonProperty("priority") @ExcludeMissing priority: JsonField = JsonMissing.of(), + @JsonProperty("updated_at") + @ExcludeMissing + updatedAt: JsonField = JsonMissing.of(), + ) : this( + id, + attributes, + conditions, + createdAt, + deletedAt, + effectiveEndDate, + effectiveStartDate, + entityType, + priority, + updatedAt, + mutableMapOf(), + ) + + /** + * Finch id (uuidv4) for the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Specifies the fields to be applied when the condition is met. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun conditions(): Optional> = conditions.getOptional("conditions") + + /** + * The datetime when the rule was created. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun createdAt(): Optional = createdAt.getOptional("created_at") + + /** + * The datetime when the rule was deleted. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun deletedAt(): Optional = deletedAt.getOptional("deleted_at") + + /** + * Specifies when the rules should stop applying rules based on the date. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun effectiveEndDate(): Optional = effectiveEndDate.getOptional("effective_end_date") + + /** + * Specifies when the rule should begin applying based on the date. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun effectiveStartDate(): Optional = + effectiveStartDate.getOptional("effective_start_date") + + /** + * The entity type to which the rule is applied. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun entityType(): Optional = entityType.getOptional("entity_type") + + /** + * The priority of the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun priority(): Optional = priority.getOptional("priority") + + /** + * The datetime when the rule was last updated. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("attributes") + @ExcludeMissing + fun _attributes(): JsonField = attributes + + /** + * Returns the raw JSON value of [conditions]. + * + * Unlike [conditions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("conditions") + @ExcludeMissing + fun _conditions(): JsonField> = conditions + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [deletedAt]. + * + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("deleted_at") + @ExcludeMissing + fun _deletedAt(): JsonField = deletedAt + + /** + * Returns the raw JSON value of [effectiveEndDate]. + * + * Unlike [effectiveEndDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("effective_end_date") + @ExcludeMissing + fun _effectiveEndDate(): JsonField = effectiveEndDate + + /** + * Returns the raw JSON value of [effectiveStartDate]. + * + * Unlike [effectiveStartDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("effective_start_date") + @ExcludeMissing + fun _effectiveStartDate(): JsonField = effectiveStartDate + + /** + * Returns the raw JSON value of [entityType]. + * + * Unlike [entityType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("entity_type") + @ExcludeMissing + fun _entityType(): JsonField = entityType + + /** + * Returns the raw JSON value of [priority]. + * + * Unlike [priority], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("priority") @ExcludeMissing fun _priority(): JsonField = priority + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("updated_at") + @ExcludeMissing + fun _updatedAt(): JsonField = updatedAt + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [RuleDeleteResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RuleDeleteResponse]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var attributes: JsonField = JsonMissing.of() + private var conditions: JsonField>? = null + private var createdAt: JsonField = JsonMissing.of() + private var deletedAt: JsonField = JsonMissing.of() + private var effectiveEndDate: JsonField = JsonMissing.of() + private var effectiveStartDate: JsonField = JsonMissing.of() + private var entityType: JsonField = JsonMissing.of() + private var priority: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(ruleDeleteResponse: RuleDeleteResponse) = apply { + id = ruleDeleteResponse.id + attributes = ruleDeleteResponse.attributes + conditions = ruleDeleteResponse.conditions.map { it.toMutableList() } + createdAt = ruleDeleteResponse.createdAt + deletedAt = ruleDeleteResponse.deletedAt + effectiveEndDate = ruleDeleteResponse.effectiveEndDate + effectiveStartDate = ruleDeleteResponse.effectiveStartDate + entityType = ruleDeleteResponse.entityType + priority = ruleDeleteResponse.priority + updatedAt = ruleDeleteResponse.updatedAt + additionalProperties = ruleDeleteResponse.additionalProperties.toMutableMap() + } + + /** Finch id (uuidv4) for the rule. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Specifies the fields to be applied when the condition is met. */ + fun attributes(attributes: Attributes) = attributes(JsonField.of(attributes)) + + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun attributes(attributes: JsonField) = apply { this.attributes = attributes } + + fun conditions(conditions: List) = conditions(JsonField.of(conditions)) + + /** + * Sets [Builder.conditions] to an arbitrary JSON value. + * + * You should usually call [Builder.conditions] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun conditions(conditions: JsonField>) = apply { + this.conditions = conditions.map { it.toMutableList() } + } + + /** + * Adds a single [Condition] to [conditions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addCondition(condition: Condition) = apply { + conditions = + (conditions ?: JsonField.of(mutableListOf())).also { + checkKnown("conditions", it).add(condition) + } + } + + /** The datetime when the rule was created. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + /** The datetime when the rule was deleted. */ + fun deletedAt(deletedAt: OffsetDateTime) = deletedAt(JsonField.of(deletedAt)) + + /** + * Sets [Builder.deletedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.deletedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun deletedAt(deletedAt: JsonField) = apply { this.deletedAt = deletedAt } + + /** Specifies when the rules should stop applying rules based on the date. */ + fun effectiveEndDate(effectiveEndDate: String?) = + effectiveEndDate(JsonField.ofNullable(effectiveEndDate)) + + /** Alias for calling [Builder.effectiveEndDate] with `effectiveEndDate.orElse(null)`. */ + fun effectiveEndDate(effectiveEndDate: Optional) = + effectiveEndDate(effectiveEndDate.getOrNull()) + + /** + * Sets [Builder.effectiveEndDate] to an arbitrary JSON value. + * + * You should usually call [Builder.effectiveEndDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun effectiveEndDate(effectiveEndDate: JsonField) = apply { + this.effectiveEndDate = effectiveEndDate + } + + /** Specifies when the rule should begin applying based on the date. */ + fun effectiveStartDate(effectiveStartDate: String?) = + effectiveStartDate(JsonField.ofNullable(effectiveStartDate)) + + /** + * Alias for calling [Builder.effectiveStartDate] with `effectiveStartDate.orElse(null)`. + */ + fun effectiveStartDate(effectiveStartDate: Optional) = + effectiveStartDate(effectiveStartDate.getOrNull()) + + /** + * Sets [Builder.effectiveStartDate] to an arbitrary JSON value. + * + * You should usually call [Builder.effectiveStartDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun effectiveStartDate(effectiveStartDate: JsonField) = apply { + this.effectiveStartDate = effectiveStartDate + } + + /** The entity type to which the rule is applied. */ + fun entityType(entityType: EntityType) = entityType(JsonField.of(entityType)) + + /** + * Sets [Builder.entityType] to an arbitrary JSON value. + * + * You should usually call [Builder.entityType] with a well-typed [EntityType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun entityType(entityType: JsonField) = apply { this.entityType = entityType } + + /** The priority of the rule. */ + fun priority(priority: Long) = priority(JsonField.of(priority)) + + /** + * Sets [Builder.priority] to an arbitrary JSON value. + * + * You should usually call [Builder.priority] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun priority(priority: JsonField) = apply { this.priority = priority } + + /** The datetime when the rule was last updated. */ + fun updatedAt(updatedAt: OffsetDateTime) = updatedAt(JsonField.of(updatedAt)) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun updatedAt(updatedAt: JsonField) = apply { this.updatedAt = updatedAt } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RuleDeleteResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RuleDeleteResponse = + RuleDeleteResponse( + id, + attributes, + (conditions ?: JsonMissing.of()).map { it.toImmutable() }, + createdAt, + deletedAt, + effectiveEndDate, + effectiveStartDate, + entityType, + priority, + updatedAt, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): RuleDeleteResponse = apply { + if (validated) { + return@apply + } + + id() + attributes().ifPresent { it.validate() } + conditions().ifPresent { it.forEach { it.validate() } } + createdAt() + deletedAt() + effectiveEndDate() + effectiveStartDate() + entityType().ifPresent { it.validate() } + priority() + updatedAt() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (conditions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (deletedAt.asKnown().isPresent) 1 else 0) + + (if (effectiveEndDate.asKnown().isPresent) 1 else 0) + + (if (effectiveStartDate.asKnown().isPresent) 1 else 0) + + (entityType.asKnown().getOrNull()?.validity() ?: 0) + + (if (priority.asKnown().isPresent) 1 else 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + /** Specifies the fields to be applied when the condition is met. */ + class Attributes + private constructor( + private val metadata: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values can + * be of any type (string, number, boolean, object, array, etc.). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Attributes]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Attributes]. */ + class Builder internal constructor() { + + private var metadata: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(attributes: Attributes) = apply { + metadata = attributes.metadata + additionalProperties = attributes.additionalProperties.toMutableMap() + } + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values + * can be of any type (string, number, boolean, object, array, etc.). + */ + fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Attributes = Attributes(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values can + * be of any type (string, number, boolean, object, array, etc.). + */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Metadata && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Attributes && metadata == other.metadata && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(metadata, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Attributes{metadata=$metadata, additionalProperties=$additionalProperties}" + } + + class Condition + private constructor( + private val field: JsonField, + private val operator: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("field") @ExcludeMissing field: JsonField = JsonMissing.of(), + @JsonProperty("operator") + @ExcludeMissing + operator: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + ) : this(field, operator, value, mutableMapOf()) + + /** + * The field to be checked in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun field(): Optional = field.getOptional("field") + + /** + * The operator to be used in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun operator(): Optional = operator.getOptional("operator") + + /** + * The value of the field to be checked in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun value(): Optional = value.getOptional("value") + + /** + * Returns the raw JSON value of [field]. + * + * Unlike [field], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("field") @ExcludeMissing fun _field(): JsonField = field + + /** + * Returns the raw JSON value of [operator]. + * + * Unlike [operator], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("operator") @ExcludeMissing fun _operator(): JsonField = operator + + /** + * Returns the raw JSON value of [value]. + * + * Unlike [value], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Condition]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Condition]. */ + class Builder internal constructor() { + + private var field: JsonField = JsonMissing.of() + private var operator: JsonField = JsonMissing.of() + private var value: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(condition: Condition) = apply { + field = condition.field + operator = condition.operator + value = condition.value + additionalProperties = condition.additionalProperties.toMutableMap() + } + + /** The field to be checked in the rule. */ + fun field(field: String) = field(JsonField.of(field)) + + /** + * Sets [Builder.field] to an arbitrary JSON value. + * + * You should usually call [Builder.field] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun field(field: JsonField) = apply { this.field = field } + + /** The operator to be used in the rule. */ + fun operator(operator: Operator) = operator(JsonField.of(operator)) + + /** + * Sets [Builder.operator] to an arbitrary JSON value. + * + * You should usually call [Builder.operator] with a well-typed [Operator] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun operator(operator: JsonField) = apply { this.operator = operator } + + /** The value of the field to be checked in the rule. */ + fun value(value: String) = value(JsonField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary JSON value. + * + * You should usually call [Builder.value] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun value(value: JsonField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Condition]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Condition = + Condition(field, operator, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Condition = apply { + if (validated) { + return@apply + } + + field() + operator().ifPresent { it.validate() } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (field.asKnown().isPresent) 1 else 0) + + (operator.asKnown().getOrNull()?.validity() ?: 0) + + (if (value.asKnown().isPresent) 1 else 0) + + /** The operator to be used in the rule. */ + class Operator @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val EQUALS = of("equals") + + @JvmStatic fun of(value: String) = Operator(JsonField.of(value)) + } + + /** An enum containing [Operator]'s known values. */ + enum class Known { + EQUALS + } + + /** + * An enum containing [Operator]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Operator] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + EQUALS, + /** + * An enum member indicating that [Operator] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + EQUALS -> Value.EQUALS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws FinchInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + EQUALS -> Known.EQUALS + else -> throw FinchInvalidDataException("Unknown Operator: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws FinchInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + FinchInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Operator = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Operator && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Condition && field == other.field && operator == other.operator && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(field, operator, value, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Condition{field=$field, operator=$operator, value=$value, additionalProperties=$additionalProperties}" + } + + /** The entity type to which the rule is applied. */ + class EntityType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PAY_STATEMENT_ITEM = of("pay_statement_item") + + @JvmStatic fun of(value: String) = EntityType(JsonField.of(value)) + } + + /** An enum containing [EntityType]'s known values. */ + enum class Known { + PAY_STATEMENT_ITEM + } + + /** + * An enum containing [EntityType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [EntityType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PAY_STATEMENT_ITEM, + /** + * An enum member indicating that [EntityType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PAY_STATEMENT_ITEM -> Value.PAY_STATEMENT_ITEM + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws FinchInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + PAY_STATEMENT_ITEM -> Known.PAY_STATEMENT_ITEM + else -> throw FinchInvalidDataException("Unknown EntityType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws FinchInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): EntityType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is EntityType && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is RuleDeleteResponse && id == other.id && attributes == other.attributes && conditions == other.conditions && createdAt == other.createdAt && deletedAt == other.deletedAt && effectiveEndDate == other.effectiveEndDate && effectiveStartDate == other.effectiveStartDate && entityType == other.entityType && priority == other.priority && updatedAt == other.updatedAt && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(id, attributes, conditions, createdAt, deletedAt, effectiveEndDate, effectiveStartDate, entityType, priority, updatedAt, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RuleDeleteResponse{id=$id, attributes=$attributes, conditions=$conditions, createdAt=$createdAt, deletedAt=$deletedAt, effectiveEndDate=$effectiveEndDate, effectiveStartDate=$effectiveStartDate, entityType=$entityType, priority=$priority, updatedAt=$updatedAt, additionalProperties=$additionalProperties}" +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RuleListResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RuleListResponse.kt new file mode 100644 index 00000000..512f1b09 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RuleListResponse.kt @@ -0,0 +1,1218 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.tryfinch.api.core.Enum +import com.tryfinch.api.core.ExcludeMissing +import com.tryfinch.api.core.JsonField +import com.tryfinch.api.core.JsonMissing +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.checkKnown +import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class RuleListResponse +private constructor( + private val id: JsonField, + private val attributes: JsonField, + private val conditions: JsonField>, + private val createdAt: JsonField, + private val effectiveEndDate: JsonField, + private val effectiveStartDate: JsonField, + private val entityType: JsonField, + private val priority: JsonField, + private val updatedAt: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("conditions") + @ExcludeMissing + conditions: JsonField> = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("effective_end_date") + @ExcludeMissing + effectiveEndDate: JsonField = JsonMissing.of(), + @JsonProperty("effective_start_date") + @ExcludeMissing + effectiveStartDate: JsonField = JsonMissing.of(), + @JsonProperty("entity_type") + @ExcludeMissing + entityType: JsonField = JsonMissing.of(), + @JsonProperty("priority") @ExcludeMissing priority: JsonField = JsonMissing.of(), + @JsonProperty("updated_at") + @ExcludeMissing + updatedAt: JsonField = JsonMissing.of(), + ) : this( + id, + attributes, + conditions, + createdAt, + effectiveEndDate, + effectiveStartDate, + entityType, + priority, + updatedAt, + mutableMapOf(), + ) + + /** + * Finch id (uuidv4) for the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Specifies the fields to be applied when the condition is met. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun conditions(): Optional> = conditions.getOptional("conditions") + + /** + * The datetime when the rule was created. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun createdAt(): Optional = createdAt.getOptional("created_at") + + /** + * Specifies when the rules should stop applying rules based on the date. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun effectiveEndDate(): Optional = effectiveEndDate.getOptional("effective_end_date") + + /** + * Specifies when the rule should begin applying based on the date. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun effectiveStartDate(): Optional = + effectiveStartDate.getOptional("effective_start_date") + + /** + * The entity type to which the rule is applied. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun entityType(): Optional = entityType.getOptional("entity_type") + + /** + * The priority of the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun priority(): Optional = priority.getOptional("priority") + + /** + * The datetime when the rule was last updated. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("attributes") + @ExcludeMissing + fun _attributes(): JsonField = attributes + + /** + * Returns the raw JSON value of [conditions]. + * + * Unlike [conditions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("conditions") + @ExcludeMissing + fun _conditions(): JsonField> = conditions + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [effectiveEndDate]. + * + * Unlike [effectiveEndDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("effective_end_date") + @ExcludeMissing + fun _effectiveEndDate(): JsonField = effectiveEndDate + + /** + * Returns the raw JSON value of [effectiveStartDate]. + * + * Unlike [effectiveStartDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("effective_start_date") + @ExcludeMissing + fun _effectiveStartDate(): JsonField = effectiveStartDate + + /** + * Returns the raw JSON value of [entityType]. + * + * Unlike [entityType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("entity_type") + @ExcludeMissing + fun _entityType(): JsonField = entityType + + /** + * Returns the raw JSON value of [priority]. + * + * Unlike [priority], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("priority") @ExcludeMissing fun _priority(): JsonField = priority + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("updated_at") + @ExcludeMissing + fun _updatedAt(): JsonField = updatedAt + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [RuleListResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RuleListResponse]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var attributes: JsonField = JsonMissing.of() + private var conditions: JsonField>? = null + private var createdAt: JsonField = JsonMissing.of() + private var effectiveEndDate: JsonField = JsonMissing.of() + private var effectiveStartDate: JsonField = JsonMissing.of() + private var entityType: JsonField = JsonMissing.of() + private var priority: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(ruleListResponse: RuleListResponse) = apply { + id = ruleListResponse.id + attributes = ruleListResponse.attributes + conditions = ruleListResponse.conditions.map { it.toMutableList() } + createdAt = ruleListResponse.createdAt + effectiveEndDate = ruleListResponse.effectiveEndDate + effectiveStartDate = ruleListResponse.effectiveStartDate + entityType = ruleListResponse.entityType + priority = ruleListResponse.priority + updatedAt = ruleListResponse.updatedAt + additionalProperties = ruleListResponse.additionalProperties.toMutableMap() + } + + /** Finch id (uuidv4) for the rule. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Specifies the fields to be applied when the condition is met. */ + fun attributes(attributes: Attributes) = attributes(JsonField.of(attributes)) + + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun attributes(attributes: JsonField) = apply { this.attributes = attributes } + + fun conditions(conditions: List) = conditions(JsonField.of(conditions)) + + /** + * Sets [Builder.conditions] to an arbitrary JSON value. + * + * You should usually call [Builder.conditions] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun conditions(conditions: JsonField>) = apply { + this.conditions = conditions.map { it.toMutableList() } + } + + /** + * Adds a single [Condition] to [conditions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addCondition(condition: Condition) = apply { + conditions = + (conditions ?: JsonField.of(mutableListOf())).also { + checkKnown("conditions", it).add(condition) + } + } + + /** The datetime when the rule was created. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + /** Specifies when the rules should stop applying rules based on the date. */ + fun effectiveEndDate(effectiveEndDate: String?) = + effectiveEndDate(JsonField.ofNullable(effectiveEndDate)) + + /** Alias for calling [Builder.effectiveEndDate] with `effectiveEndDate.orElse(null)`. */ + fun effectiveEndDate(effectiveEndDate: Optional) = + effectiveEndDate(effectiveEndDate.getOrNull()) + + /** + * Sets [Builder.effectiveEndDate] to an arbitrary JSON value. + * + * You should usually call [Builder.effectiveEndDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun effectiveEndDate(effectiveEndDate: JsonField) = apply { + this.effectiveEndDate = effectiveEndDate + } + + /** Specifies when the rule should begin applying based on the date. */ + fun effectiveStartDate(effectiveStartDate: String?) = + effectiveStartDate(JsonField.ofNullable(effectiveStartDate)) + + /** + * Alias for calling [Builder.effectiveStartDate] with `effectiveStartDate.orElse(null)`. + */ + fun effectiveStartDate(effectiveStartDate: Optional) = + effectiveStartDate(effectiveStartDate.getOrNull()) + + /** + * Sets [Builder.effectiveStartDate] to an arbitrary JSON value. + * + * You should usually call [Builder.effectiveStartDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun effectiveStartDate(effectiveStartDate: JsonField) = apply { + this.effectiveStartDate = effectiveStartDate + } + + /** The entity type to which the rule is applied. */ + fun entityType(entityType: EntityType) = entityType(JsonField.of(entityType)) + + /** + * Sets [Builder.entityType] to an arbitrary JSON value. + * + * You should usually call [Builder.entityType] with a well-typed [EntityType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun entityType(entityType: JsonField) = apply { this.entityType = entityType } + + /** The priority of the rule. */ + fun priority(priority: Long) = priority(JsonField.of(priority)) + + /** + * Sets [Builder.priority] to an arbitrary JSON value. + * + * You should usually call [Builder.priority] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun priority(priority: JsonField) = apply { this.priority = priority } + + /** The datetime when the rule was last updated. */ + fun updatedAt(updatedAt: OffsetDateTime) = updatedAt(JsonField.of(updatedAt)) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun updatedAt(updatedAt: JsonField) = apply { this.updatedAt = updatedAt } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RuleListResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RuleListResponse = + RuleListResponse( + id, + attributes, + (conditions ?: JsonMissing.of()).map { it.toImmutable() }, + createdAt, + effectiveEndDate, + effectiveStartDate, + entityType, + priority, + updatedAt, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): RuleListResponse = apply { + if (validated) { + return@apply + } + + id() + attributes().ifPresent { it.validate() } + conditions().ifPresent { it.forEach { it.validate() } } + createdAt() + effectiveEndDate() + effectiveStartDate() + entityType().ifPresent { it.validate() } + priority() + updatedAt() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (conditions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (effectiveEndDate.asKnown().isPresent) 1 else 0) + + (if (effectiveStartDate.asKnown().isPresent) 1 else 0) + + (entityType.asKnown().getOrNull()?.validity() ?: 0) + + (if (priority.asKnown().isPresent) 1 else 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + /** Specifies the fields to be applied when the condition is met. */ + class Attributes + private constructor( + private val metadata: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values can + * be of any type (string, number, boolean, object, array, etc.). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Attributes]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Attributes]. */ + class Builder internal constructor() { + + private var metadata: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(attributes: Attributes) = apply { + metadata = attributes.metadata + additionalProperties = attributes.additionalProperties.toMutableMap() + } + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values + * can be of any type (string, number, boolean, object, array, etc.). + */ + fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Attributes = Attributes(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values can + * be of any type (string, number, boolean, object, array, etc.). + */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Metadata && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Attributes && metadata == other.metadata && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(metadata, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Attributes{metadata=$metadata, additionalProperties=$additionalProperties}" + } + + class Condition + private constructor( + private val field: JsonField, + private val operator: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("field") @ExcludeMissing field: JsonField = JsonMissing.of(), + @JsonProperty("operator") + @ExcludeMissing + operator: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + ) : this(field, operator, value, mutableMapOf()) + + /** + * The field to be checked in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun field(): Optional = field.getOptional("field") + + /** + * The operator to be used in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun operator(): Optional = operator.getOptional("operator") + + /** + * The value of the field to be checked in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun value(): Optional = value.getOptional("value") + + /** + * Returns the raw JSON value of [field]. + * + * Unlike [field], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("field") @ExcludeMissing fun _field(): JsonField = field + + /** + * Returns the raw JSON value of [operator]. + * + * Unlike [operator], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("operator") @ExcludeMissing fun _operator(): JsonField = operator + + /** + * Returns the raw JSON value of [value]. + * + * Unlike [value], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Condition]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Condition]. */ + class Builder internal constructor() { + + private var field: JsonField = JsonMissing.of() + private var operator: JsonField = JsonMissing.of() + private var value: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(condition: Condition) = apply { + field = condition.field + operator = condition.operator + value = condition.value + additionalProperties = condition.additionalProperties.toMutableMap() + } + + /** The field to be checked in the rule. */ + fun field(field: String) = field(JsonField.of(field)) + + /** + * Sets [Builder.field] to an arbitrary JSON value. + * + * You should usually call [Builder.field] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun field(field: JsonField) = apply { this.field = field } + + /** The operator to be used in the rule. */ + fun operator(operator: Operator) = operator(JsonField.of(operator)) + + /** + * Sets [Builder.operator] to an arbitrary JSON value. + * + * You should usually call [Builder.operator] with a well-typed [Operator] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun operator(operator: JsonField) = apply { this.operator = operator } + + /** The value of the field to be checked in the rule. */ + fun value(value: String) = value(JsonField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary JSON value. + * + * You should usually call [Builder.value] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun value(value: JsonField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Condition]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Condition = + Condition(field, operator, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Condition = apply { + if (validated) { + return@apply + } + + field() + operator().ifPresent { it.validate() } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (field.asKnown().isPresent) 1 else 0) + + (operator.asKnown().getOrNull()?.validity() ?: 0) + + (if (value.asKnown().isPresent) 1 else 0) + + /** The operator to be used in the rule. */ + class Operator @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val EQUALS = of("equals") + + @JvmStatic fun of(value: String) = Operator(JsonField.of(value)) + } + + /** An enum containing [Operator]'s known values. */ + enum class Known { + EQUALS + } + + /** + * An enum containing [Operator]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Operator] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + EQUALS, + /** + * An enum member indicating that [Operator] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + EQUALS -> Value.EQUALS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws FinchInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + EQUALS -> Known.EQUALS + else -> throw FinchInvalidDataException("Unknown Operator: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws FinchInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + FinchInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Operator = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Operator && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Condition && field == other.field && operator == other.operator && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(field, operator, value, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Condition{field=$field, operator=$operator, value=$value, additionalProperties=$additionalProperties}" + } + + /** The entity type to which the rule is applied. */ + class EntityType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PAY_STATEMENT_ITEM = of("pay_statement_item") + + @JvmStatic fun of(value: String) = EntityType(JsonField.of(value)) + } + + /** An enum containing [EntityType]'s known values. */ + enum class Known { + PAY_STATEMENT_ITEM + } + + /** + * An enum containing [EntityType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [EntityType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PAY_STATEMENT_ITEM, + /** + * An enum member indicating that [EntityType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PAY_STATEMENT_ITEM -> Value.PAY_STATEMENT_ITEM + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws FinchInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + PAY_STATEMENT_ITEM -> Known.PAY_STATEMENT_ITEM + else -> throw FinchInvalidDataException("Unknown EntityType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws FinchInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): EntityType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is EntityType && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is RuleListResponse && id == other.id && attributes == other.attributes && conditions == other.conditions && createdAt == other.createdAt && effectiveEndDate == other.effectiveEndDate && effectiveStartDate == other.effectiveStartDate && entityType == other.entityType && priority == other.priority && updatedAt == other.updatedAt && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(id, attributes, conditions, createdAt, effectiveEndDate, effectiveStartDate, entityType, priority, updatedAt, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RuleListResponse{id=$id, attributes=$attributes, conditions=$conditions, createdAt=$createdAt, effectiveEndDate=$effectiveEndDate, effectiveStartDate=$effectiveStartDate, entityType=$entityType, priority=$priority, updatedAt=$updatedAt, additionalProperties=$additionalProperties}" +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RuleUpdateResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RuleUpdateResponse.kt new file mode 100644 index 00000000..d8735c62 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/RuleUpdateResponse.kt @@ -0,0 +1,1218 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.tryfinch.api.core.Enum +import com.tryfinch.api.core.ExcludeMissing +import com.tryfinch.api.core.JsonField +import com.tryfinch.api.core.JsonMissing +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.checkKnown +import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class RuleUpdateResponse +private constructor( + private val id: JsonField, + private val attributes: JsonField, + private val conditions: JsonField>, + private val createdAt: JsonField, + private val effectiveEndDate: JsonField, + private val effectiveStartDate: JsonField, + private val entityType: JsonField, + private val priority: JsonField, + private val updatedAt: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("conditions") + @ExcludeMissing + conditions: JsonField> = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("effective_end_date") + @ExcludeMissing + effectiveEndDate: JsonField = JsonMissing.of(), + @JsonProperty("effective_start_date") + @ExcludeMissing + effectiveStartDate: JsonField = JsonMissing.of(), + @JsonProperty("entity_type") + @ExcludeMissing + entityType: JsonField = JsonMissing.of(), + @JsonProperty("priority") @ExcludeMissing priority: JsonField = JsonMissing.of(), + @JsonProperty("updated_at") + @ExcludeMissing + updatedAt: JsonField = JsonMissing.of(), + ) : this( + id, + attributes, + conditions, + createdAt, + effectiveEndDate, + effectiveStartDate, + entityType, + priority, + updatedAt, + mutableMapOf(), + ) + + /** + * Finch id (uuidv4) for the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * Specifies the fields to be applied when the condition is met. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun conditions(): Optional> = conditions.getOptional("conditions") + + /** + * The datetime when the rule was created. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun createdAt(): Optional = createdAt.getOptional("created_at") + + /** + * Specifies when the rules should stop applying rules based on the date. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun effectiveEndDate(): Optional = effectiveEndDate.getOptional("effective_end_date") + + /** + * Specifies when the rule should begin applying based on the date. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun effectiveStartDate(): Optional = + effectiveStartDate.getOptional("effective_start_date") + + /** + * The entity type to which the rule is applied. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun entityType(): Optional = entityType.getOptional("entity_type") + + /** + * The priority of the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun priority(): Optional = priority.getOptional("priority") + + /** + * The datetime when the rule was last updated. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("attributes") + @ExcludeMissing + fun _attributes(): JsonField = attributes + + /** + * Returns the raw JSON value of [conditions]. + * + * Unlike [conditions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("conditions") + @ExcludeMissing + fun _conditions(): JsonField> = conditions + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [effectiveEndDate]. + * + * Unlike [effectiveEndDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("effective_end_date") + @ExcludeMissing + fun _effectiveEndDate(): JsonField = effectiveEndDate + + /** + * Returns the raw JSON value of [effectiveStartDate]. + * + * Unlike [effectiveStartDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("effective_start_date") + @ExcludeMissing + fun _effectiveStartDate(): JsonField = effectiveStartDate + + /** + * Returns the raw JSON value of [entityType]. + * + * Unlike [entityType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("entity_type") + @ExcludeMissing + fun _entityType(): JsonField = entityType + + /** + * Returns the raw JSON value of [priority]. + * + * Unlike [priority], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("priority") @ExcludeMissing fun _priority(): JsonField = priority + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("updated_at") + @ExcludeMissing + fun _updatedAt(): JsonField = updatedAt + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [RuleUpdateResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RuleUpdateResponse]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var attributes: JsonField = JsonMissing.of() + private var conditions: JsonField>? = null + private var createdAt: JsonField = JsonMissing.of() + private var effectiveEndDate: JsonField = JsonMissing.of() + private var effectiveStartDate: JsonField = JsonMissing.of() + private var entityType: JsonField = JsonMissing.of() + private var priority: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(ruleUpdateResponse: RuleUpdateResponse) = apply { + id = ruleUpdateResponse.id + attributes = ruleUpdateResponse.attributes + conditions = ruleUpdateResponse.conditions.map { it.toMutableList() } + createdAt = ruleUpdateResponse.createdAt + effectiveEndDate = ruleUpdateResponse.effectiveEndDate + effectiveStartDate = ruleUpdateResponse.effectiveStartDate + entityType = ruleUpdateResponse.entityType + priority = ruleUpdateResponse.priority + updatedAt = ruleUpdateResponse.updatedAt + additionalProperties = ruleUpdateResponse.additionalProperties.toMutableMap() + } + + /** Finch id (uuidv4) for the rule. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Specifies the fields to be applied when the condition is met. */ + fun attributes(attributes: Attributes) = attributes(JsonField.of(attributes)) + + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun attributes(attributes: JsonField) = apply { this.attributes = attributes } + + fun conditions(conditions: List) = conditions(JsonField.of(conditions)) + + /** + * Sets [Builder.conditions] to an arbitrary JSON value. + * + * You should usually call [Builder.conditions] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun conditions(conditions: JsonField>) = apply { + this.conditions = conditions.map { it.toMutableList() } + } + + /** + * Adds a single [Condition] to [conditions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addCondition(condition: Condition) = apply { + conditions = + (conditions ?: JsonField.of(mutableListOf())).also { + checkKnown("conditions", it).add(condition) + } + } + + /** The datetime when the rule was created. */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + /** Specifies when the rules should stop applying rules based on the date. */ + fun effectiveEndDate(effectiveEndDate: String?) = + effectiveEndDate(JsonField.ofNullable(effectiveEndDate)) + + /** Alias for calling [Builder.effectiveEndDate] with `effectiveEndDate.orElse(null)`. */ + fun effectiveEndDate(effectiveEndDate: Optional) = + effectiveEndDate(effectiveEndDate.getOrNull()) + + /** + * Sets [Builder.effectiveEndDate] to an arbitrary JSON value. + * + * You should usually call [Builder.effectiveEndDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun effectiveEndDate(effectiveEndDate: JsonField) = apply { + this.effectiveEndDate = effectiveEndDate + } + + /** Specifies when the rule should begin applying based on the date. */ + fun effectiveStartDate(effectiveStartDate: String?) = + effectiveStartDate(JsonField.ofNullable(effectiveStartDate)) + + /** + * Alias for calling [Builder.effectiveStartDate] with `effectiveStartDate.orElse(null)`. + */ + fun effectiveStartDate(effectiveStartDate: Optional) = + effectiveStartDate(effectiveStartDate.getOrNull()) + + /** + * Sets [Builder.effectiveStartDate] to an arbitrary JSON value. + * + * You should usually call [Builder.effectiveStartDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun effectiveStartDate(effectiveStartDate: JsonField) = apply { + this.effectiveStartDate = effectiveStartDate + } + + /** The entity type to which the rule is applied. */ + fun entityType(entityType: EntityType) = entityType(JsonField.of(entityType)) + + /** + * Sets [Builder.entityType] to an arbitrary JSON value. + * + * You should usually call [Builder.entityType] with a well-typed [EntityType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun entityType(entityType: JsonField) = apply { this.entityType = entityType } + + /** The priority of the rule. */ + fun priority(priority: Long) = priority(JsonField.of(priority)) + + /** + * Sets [Builder.priority] to an arbitrary JSON value. + * + * You should usually call [Builder.priority] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun priority(priority: JsonField) = apply { this.priority = priority } + + /** The datetime when the rule was last updated. */ + fun updatedAt(updatedAt: OffsetDateTime) = updatedAt(JsonField.of(updatedAt)) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun updatedAt(updatedAt: JsonField) = apply { this.updatedAt = updatedAt } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RuleUpdateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RuleUpdateResponse = + RuleUpdateResponse( + id, + attributes, + (conditions ?: JsonMissing.of()).map { it.toImmutable() }, + createdAt, + effectiveEndDate, + effectiveStartDate, + entityType, + priority, + updatedAt, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): RuleUpdateResponse = apply { + if (validated) { + return@apply + } + + id() + attributes().ifPresent { it.validate() } + conditions().ifPresent { it.forEach { it.validate() } } + createdAt() + effectiveEndDate() + effectiveStartDate() + entityType().ifPresent { it.validate() } + priority() + updatedAt() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (conditions.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (effectiveEndDate.asKnown().isPresent) 1 else 0) + + (if (effectiveStartDate.asKnown().isPresent) 1 else 0) + + (entityType.asKnown().getOrNull()?.validity() ?: 0) + + (if (priority.asKnown().isPresent) 1 else 0) + + (if (updatedAt.asKnown().isPresent) 1 else 0) + + /** Specifies the fields to be applied when the condition is met. */ + class Attributes + private constructor( + private val metadata: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values can + * be of any type (string, number, boolean, object, array, etc.). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Attributes]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Attributes]. */ + class Builder internal constructor() { + + private var metadata: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(attributes: Attributes) = apply { + metadata = attributes.metadata + additionalProperties = attributes.additionalProperties.toMutableMap() + } + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values + * can be of any type (string, number, boolean, object, array, etc.). + */ + fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Attributes = Attributes(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + + /** + * The metadata to be attached in the entity. It is a key-value pairs where the values can + * be of any type (string, number, boolean, object, array, etc.). + */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Metadata && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Attributes && metadata == other.metadata && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(metadata, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Attributes{metadata=$metadata, additionalProperties=$additionalProperties}" + } + + class Condition + private constructor( + private val field: JsonField, + private val operator: JsonField, + private val value: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("field") @ExcludeMissing field: JsonField = JsonMissing.of(), + @JsonProperty("operator") + @ExcludeMissing + operator: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonField = JsonMissing.of(), + ) : this(field, operator, value, mutableMapOf()) + + /** + * The field to be checked in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun field(): Optional = field.getOptional("field") + + /** + * The operator to be used in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun operator(): Optional = operator.getOptional("operator") + + /** + * The value of the field to be checked in the rule. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun value(): Optional = value.getOptional("value") + + /** + * Returns the raw JSON value of [field]. + * + * Unlike [field], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("field") @ExcludeMissing fun _field(): JsonField = field + + /** + * Returns the raw JSON value of [operator]. + * + * Unlike [operator], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("operator") @ExcludeMissing fun _operator(): JsonField = operator + + /** + * Returns the raw JSON value of [value]. + * + * Unlike [value], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("value") @ExcludeMissing fun _value(): JsonField = value + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Condition]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Condition]. */ + class Builder internal constructor() { + + private var field: JsonField = JsonMissing.of() + private var operator: JsonField = JsonMissing.of() + private var value: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(condition: Condition) = apply { + field = condition.field + operator = condition.operator + value = condition.value + additionalProperties = condition.additionalProperties.toMutableMap() + } + + /** The field to be checked in the rule. */ + fun field(field: String) = field(JsonField.of(field)) + + /** + * Sets [Builder.field] to an arbitrary JSON value. + * + * You should usually call [Builder.field] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun field(field: JsonField) = apply { this.field = field } + + /** The operator to be used in the rule. */ + fun operator(operator: Operator) = operator(JsonField.of(operator)) + + /** + * Sets [Builder.operator] to an arbitrary JSON value. + * + * You should usually call [Builder.operator] with a well-typed [Operator] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun operator(operator: JsonField) = apply { this.operator = operator } + + /** The value of the field to be checked in the rule. */ + fun value(value: String) = value(JsonField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary JSON value. + * + * You should usually call [Builder.value] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun value(value: JsonField) = apply { this.value = value } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Condition]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Condition = + Condition(field, operator, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Condition = apply { + if (validated) { + return@apply + } + + field() + operator().ifPresent { it.validate() } + value() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (field.asKnown().isPresent) 1 else 0) + + (operator.asKnown().getOrNull()?.validity() ?: 0) + + (if (value.asKnown().isPresent) 1 else 0) + + /** The operator to be used in the rule. */ + class Operator @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val EQUALS = of("equals") + + @JvmStatic fun of(value: String) = Operator(JsonField.of(value)) + } + + /** An enum containing [Operator]'s known values. */ + enum class Known { + EQUALS + } + + /** + * An enum containing [Operator]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Operator] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + EQUALS, + /** + * An enum member indicating that [Operator] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + EQUALS -> Value.EQUALS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws FinchInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + EQUALS -> Known.EQUALS + else -> throw FinchInvalidDataException("Unknown Operator: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws FinchInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + FinchInvalidDataException("Value is not a String") + } + + private var validated: Boolean = false + + fun validate(): Operator = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Operator && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Condition && field == other.field && operator == other.operator && value == other.value && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(field, operator, value, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Condition{field=$field, operator=$operator, value=$value, additionalProperties=$additionalProperties}" + } + + /** The entity type to which the rule is applied. */ + class EntityType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PAY_STATEMENT_ITEM = of("pay_statement_item") + + @JvmStatic fun of(value: String) = EntityType(JsonField.of(value)) + } + + /** An enum containing [EntityType]'s known values. */ + enum class Known { + PAY_STATEMENT_ITEM + } + + /** + * An enum containing [EntityType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [EntityType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PAY_STATEMENT_ITEM, + /** + * An enum member indicating that [EntityType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PAY_STATEMENT_ITEM -> Value.PAY_STATEMENT_ITEM + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws FinchInvalidDataException if this class instance's value is a not a known member. + */ + fun known(): Known = + when (this) { + PAY_STATEMENT_ITEM -> Known.PAY_STATEMENT_ITEM + else -> throw FinchInvalidDataException("Unknown EntityType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws FinchInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): EntityType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is EntityType && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is RuleUpdateResponse && id == other.id && attributes == other.attributes && conditions == other.conditions && createdAt == other.createdAt && effectiveEndDate == other.effectiveEndDate && effectiveStartDate == other.effectiveStartDate && entityType == other.entityType && priority == other.priority && updatedAt == other.updatedAt && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(id, attributes, conditions, createdAt, effectiveEndDate, effectiveStartDate, entityType, priority, updatedAt, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RuleUpdateResponse{id=$id, attributes=$attributes, conditions=$conditions, createdAt=$createdAt, effectiveEndDate=$effectiveEndDate, effectiveStartDate=$effectiveStartDate, entityType=$entityType, priority=$priority, updatedAt=$updatedAt, additionalProperties=$additionalProperties}" +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxCompanyUpdateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxCompanyUpdateParams.kt index d4593243..4c71017d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxCompanyUpdateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxCompanyUpdateParams.kt @@ -11,16 +11,17 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Update a sandbox company's data */ class SandboxCompanyUpdateParams @@ -30,50 +31,123 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { - /** An array of bank account objects associated with the payroll/HRIS system. */ + /** + * An array of bank account objects associated with the payroll/HRIS system. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun accounts(): Optional> = body.accounts() - /** The array of company departments. */ + /** + * The array of company departments. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun departments(): Optional> = body.departments() - /** The employer identification number. */ + /** + * The employer identification number. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun ein(): Optional = body.ein() - /** The entity type object. */ + /** + * The entity type object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun entity(): Optional = body.entity() - /** The legal name of the company. */ + /** + * The legal name of the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun legalName(): Optional = body.legalName() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun locations(): Optional> = body.locations() - /** The email of the main administrator on the account. */ + /** + * The email of the main administrator on the account. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun primaryEmail(): Optional = body.primaryEmail() - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ + /** + * The phone number of the main administrator on the account. Format: `XXXXXXXXXX` + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun primaryPhoneNumber(): Optional = body.primaryPhoneNumber() - /** An array of bank account objects associated with the payroll/HRIS system. */ + /** + * Returns the raw JSON value of [accounts]. + * + * Unlike [accounts], this method doesn't throw if the JSON field has an unexpected type. + */ fun _accounts(): JsonField> = body._accounts() - /** The array of company departments. */ + /** + * Returns the raw JSON value of [departments]. + * + * Unlike [departments], this method doesn't throw if the JSON field has an unexpected type. + */ fun _departments(): JsonField> = body._departments() - /** The employer identification number. */ + /** + * Returns the raw JSON value of [ein]. + * + * Unlike [ein], this method doesn't throw if the JSON field has an unexpected type. + */ fun _ein(): JsonField = body._ein() - /** The entity type object. */ + /** + * Returns the raw JSON value of [entity]. + * + * Unlike [entity], this method doesn't throw if the JSON field has an unexpected type. + */ fun _entity(): JsonField = body._entity() - /** The legal name of the company. */ + /** + * Returns the raw JSON value of [legalName]. + * + * Unlike [legalName], this method doesn't throw if the JSON field has an unexpected type. + */ fun _legalName(): JsonField = body._legalName() + /** + * Returns the raw JSON value of [locations]. + * + * Unlike [locations], this method doesn't throw if the JSON field has an unexpected type. + */ fun _locations(): JsonField> = body._locations() - /** The email of the main administrator on the account. */ + /** + * Returns the raw JSON value of [primaryEmail]. + * + * Unlike [primaryEmail], this method doesn't throw if the JSON field has an unexpected type. + */ fun _primaryEmail(): JsonField = body._primaryEmail() - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ + /** + * Returns the raw JSON value of [primaryPhoneNumber]. + * + * Unlike [primaryPhoneNumber], this method doesn't throw if the JSON field has an unexpected + * type. + */ fun _primaryPhoneNumber(): JsonField = body._primaryPhoneNumber() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -82,664 +156,1018 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): CompanyWithoutId = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of [SandboxCompanyUpdateParams]. + * + * The following fields are required: + * ```java + * .accounts() + * .departments() + * .ein() + * .entity() + * .legalName() + * .locations() + * .primaryEmail() + * .primaryPhoneNumber() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - @NoAutoDetect - class CompanyWithoutId - @JsonCreator - private constructor( - @JsonProperty("accounts") - @ExcludeMissing - private val accounts: JsonField> = JsonMissing.of(), - @JsonProperty("departments") - @ExcludeMissing - private val departments: JsonField> = JsonMissing.of(), - @JsonProperty("ein") @ExcludeMissing private val ein: JsonField = JsonMissing.of(), - @JsonProperty("entity") - @ExcludeMissing - private val entity: JsonField = JsonMissing.of(), - @JsonProperty("legal_name") - @ExcludeMissing - private val legalName: JsonField = JsonMissing.of(), - @JsonProperty("locations") - @ExcludeMissing - private val locations: JsonField> = JsonMissing.of(), - @JsonProperty("primary_email") - @ExcludeMissing - private val primaryEmail: JsonField = JsonMissing.of(), - @JsonProperty("primary_phone_number") - @ExcludeMissing - private val primaryPhoneNumber: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** A builder for [SandboxCompanyUpdateParams]. */ + class Builder internal constructor() { - /** An array of bank account objects associated with the payroll/HRIS system. */ - fun accounts(): Optional> = - Optional.ofNullable(accounts.getNullable("accounts")) + private var body: CompanyWithoutId.Builder = CompanyWithoutId.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - /** The array of company departments. */ - fun departments(): Optional> = - Optional.ofNullable(departments.getNullable("departments")) + @JvmSynthetic + internal fun from(sandboxCompanyUpdateParams: SandboxCompanyUpdateParams) = apply { + body = sandboxCompanyUpdateParams.body.toBuilder() + additionalHeaders = sandboxCompanyUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = sandboxCompanyUpdateParams.additionalQueryParams.toBuilder() + } - /** The employer identification number. */ - fun ein(): Optional = Optional.ofNullable(ein.getNullable("ein")) + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [accounts] + * - [departments] + * - [ein] + * - [entity] + * - [legalName] + * - etc. + */ + fun body(body: CompanyWithoutId) = apply { this.body = body.toBuilder() } - /** The entity type object. */ - fun entity(): Optional = Optional.ofNullable(entity.getNullable("entity")) + /** An array of bank account objects associated with the payroll/HRIS system. */ + fun accounts(accounts: List?) = apply { body.accounts(accounts) } - /** The legal name of the company. */ - fun legalName(): Optional = Optional.ofNullable(legalName.getNullable("legal_name")) + /** Alias for calling [Builder.accounts] with `accounts.orElse(null)`. */ + fun accounts(accounts: Optional>) = accounts(accounts.getOrNull()) - fun locations(): Optional> = - Optional.ofNullable(locations.getNullable("locations")) + /** + * Sets [Builder.accounts] to an arbitrary JSON value. + * + * You should usually call [Builder.accounts] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun accounts(accounts: JsonField>) = apply { body.accounts(accounts) } - /** The email of the main administrator on the account. */ - fun primaryEmail(): Optional = - Optional.ofNullable(primaryEmail.getNullable("primary_email")) + /** + * Adds a single [Account] to [accounts]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAccount(account: Account) = apply { body.addAccount(account) } - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ - fun primaryPhoneNumber(): Optional = - Optional.ofNullable(primaryPhoneNumber.getNullable("primary_phone_number")) + /** The array of company departments. */ + fun departments(departments: List?) = apply { body.departments(departments) } - /** An array of bank account objects associated with the payroll/HRIS system. */ - @JsonProperty("accounts") - @ExcludeMissing - fun _accounts(): JsonField> = accounts + /** Alias for calling [Builder.departments] with `departments.orElse(null)`. */ + fun departments(departments: Optional>) = + departments(departments.getOrNull()) - /** The array of company departments. */ - @JsonProperty("departments") - @ExcludeMissing - fun _departments(): JsonField> = departments + /** + * Sets [Builder.departments] to an arbitrary JSON value. + * + * You should usually call [Builder.departments] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun departments(departments: JsonField>) = apply { + body.departments(departments) + } + + /** + * Adds a single [Department] to [departments]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addDepartment(department: Department) = apply { body.addDepartment(department) } /** The employer identification number. */ - @JsonProperty("ein") @ExcludeMissing fun _ein(): JsonField = ein + fun ein(ein: String?) = apply { body.ein(ein) } + + /** Alias for calling [Builder.ein] with `ein.orElse(null)`. */ + fun ein(ein: Optional) = ein(ein.getOrNull()) + + /** + * Sets [Builder.ein] to an arbitrary JSON value. + * + * You should usually call [Builder.ein] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun ein(ein: JsonField) = apply { body.ein(ein) } /** The entity type object. */ - @JsonProperty("entity") @ExcludeMissing fun _entity(): JsonField = entity + fun entity(entity: Entity?) = apply { body.entity(entity) } - /** The legal name of the company. */ - @JsonProperty("legal_name") @ExcludeMissing fun _legalName(): JsonField = legalName + /** Alias for calling [Builder.entity] with `entity.orElse(null)`. */ + fun entity(entity: Optional) = entity(entity.getOrNull()) - @JsonProperty("locations") - @ExcludeMissing - fun _locations(): JsonField> = locations + /** + * Sets [Builder.entity] to an arbitrary JSON value. + * + * You should usually call [Builder.entity] with a well-typed [Entity] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun entity(entity: JsonField) = apply { body.entity(entity) } - /** The email of the main administrator on the account. */ - @JsonProperty("primary_email") - @ExcludeMissing - fun _primaryEmail(): JsonField = primaryEmail + /** The legal name of the company. */ + fun legalName(legalName: String?) = apply { body.legalName(legalName) } - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ - @JsonProperty("primary_phone_number") - @ExcludeMissing - fun _primaryPhoneNumber(): JsonField = primaryPhoneNumber + /** Alias for calling [Builder.legalName] with `legalName.orElse(null)`. */ + fun legalName(legalName: Optional) = legalName(legalName.getOrNull()) - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** + * Sets [Builder.legalName] to an arbitrary JSON value. + * + * You should usually call [Builder.legalName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun legalName(legalName: JsonField) = apply { body.legalName(legalName) } - private var validated: Boolean = false + fun locations(locations: List?) = apply { body.locations(locations) } - fun validate(): CompanyWithoutId = apply { - if (validated) { - return@apply - } + /** Alias for calling [Builder.locations] with `locations.orElse(null)`. */ + fun locations(locations: Optional>) = locations(locations.getOrNull()) - accounts().ifPresent { it.forEach { it.validate() } } - departments().ifPresent { it.forEach { it?.validate() } } - ein() - entity().ifPresent { it.validate() } - legalName() - locations().ifPresent { it.forEach { it?.validate() } } - primaryEmail() - primaryPhoneNumber() - validated = true - } + /** + * Sets [Builder.locations] to an arbitrary JSON value. + * + * You should usually call [Builder.locations] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun locations(locations: JsonField>) = apply { body.locations(locations) } - fun toBuilder() = Builder().from(this) + /** + * Adds a single [Location] to [locations]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addLocation(location: Location) = apply { body.addLocation(location) } - companion object { + /** The email of the main administrator on the account. */ + fun primaryEmail(primaryEmail: String?) = apply { body.primaryEmail(primaryEmail) } - @JvmStatic fun builder() = Builder() + /** Alias for calling [Builder.primaryEmail] with `primaryEmail.orElse(null)`. */ + fun primaryEmail(primaryEmail: Optional) = primaryEmail(primaryEmail.getOrNull()) + + /** + * Sets [Builder.primaryEmail] to an arbitrary JSON value. + * + * You should usually call [Builder.primaryEmail] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun primaryEmail(primaryEmail: JsonField) = apply { + body.primaryEmail(primaryEmail) } - /** A builder for [CompanyWithoutId]. */ - class Builder internal constructor() { + /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ + fun primaryPhoneNumber(primaryPhoneNumber: String?) = apply { + body.primaryPhoneNumber(primaryPhoneNumber) + } - private var accounts: JsonField>? = null - private var departments: JsonField>? = null - private var ein: JsonField? = null - private var entity: JsonField? = null - private var legalName: JsonField? = null - private var locations: JsonField>? = null - private var primaryEmail: JsonField? = null - private var primaryPhoneNumber: JsonField? = null - private var additionalProperties: MutableMap = mutableMapOf() + /** + * Alias for calling [Builder.primaryPhoneNumber] with `primaryPhoneNumber.orElse(null)`. + */ + fun primaryPhoneNumber(primaryPhoneNumber: Optional) = + primaryPhoneNumber(primaryPhoneNumber.getOrNull()) - @JvmSynthetic - internal fun from(companyWithoutId: CompanyWithoutId) = apply { - accounts = companyWithoutId.accounts.map { it.toMutableList() } - departments = companyWithoutId.departments.map { it.toMutableList() } - ein = companyWithoutId.ein - entity = companyWithoutId.entity - legalName = companyWithoutId.legalName - locations = companyWithoutId.locations.map { it.toMutableList() } - primaryEmail = companyWithoutId.primaryEmail - primaryPhoneNumber = companyWithoutId.primaryPhoneNumber - additionalProperties = companyWithoutId.additionalProperties.toMutableMap() - } + /** + * Sets [Builder.primaryPhoneNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.primaryPhoneNumber] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun primaryPhoneNumber(primaryPhoneNumber: JsonField) = apply { + body.primaryPhoneNumber(primaryPhoneNumber) + } - /** An array of bank account objects associated with the payroll/HRIS system. */ - fun accounts(accounts: List?) = accounts(JsonField.ofNullable(accounts)) + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - /** An array of bank account objects associated with the payroll/HRIS system. */ - fun accounts(accounts: Optional>) = accounts(accounts.orElse(null)) + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - /** An array of bank account objects associated with the payroll/HRIS system. */ - fun accounts(accounts: JsonField>) = apply { - this.accounts = accounts.map { it.toMutableList() } + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** An array of bank account objects associated with the payroll/HRIS system. */ - fun addAccount(account: Account) = apply { - accounts = - (accounts ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(account) - } - } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** The array of company departments. */ - fun departments(departments: List?) = - departments(JsonField.ofNullable(departments)) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** The array of company departments. */ - fun departments(departments: Optional>) = - departments(departments.orElse(null)) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** The array of company departments. */ - fun departments(departments: JsonField>) = apply { - this.departments = departments.map { it.toMutableList() } - } + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** The array of company departments. */ - fun addDepartment(department: Department) = apply { - departments = - (departments ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(department) - } - } + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** The employer identification number. */ - fun ein(ein: String?) = ein(JsonField.ofNullable(ein)) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** The employer identification number. */ - fun ein(ein: Optional) = ein(ein.orElse(null)) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** The employer identification number. */ - fun ein(ein: JsonField) = apply { this.ein = ein } + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** The entity type object. */ - fun entity(entity: Entity?) = entity(JsonField.ofNullable(entity)) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** The entity type object. */ - fun entity(entity: Optional) = entity(entity.orElse(null)) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** The entity type object. */ - fun entity(entity: JsonField) = apply { this.entity = entity } + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** The legal name of the company. */ - fun legalName(legalName: String?) = legalName(JsonField.ofNullable(legalName)) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** The legal name of the company. */ - fun legalName(legalName: Optional) = legalName(legalName.orElse(null)) - - /** The legal name of the company. */ - fun legalName(legalName: JsonField) = apply { this.legalName = legalName } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun locations(locations: List?) = locations(JsonField.ofNullable(locations)) + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun locations(locations: Optional>) = locations(locations.orElse(null)) + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun locations(locations: JsonField>) = apply { - this.locations = locations.map { it.toMutableList() } - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun addLocation(location: Location) = apply { - locations = - (locations ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(location) - } - } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - /** The email of the main administrator on the account. */ - fun primaryEmail(primaryEmail: String?) = - primaryEmail(JsonField.ofNullable(primaryEmail)) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** The email of the main administrator on the account. */ - fun primaryEmail(primaryEmail: Optional) = - primaryEmail(primaryEmail.orElse(null)) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - /** The email of the main administrator on the account. */ - fun primaryEmail(primaryEmail: JsonField) = apply { - this.primaryEmail = primaryEmail + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ - fun primaryPhoneNumber(primaryPhoneNumber: String?) = - primaryPhoneNumber(JsonField.ofNullable(primaryPhoneNumber)) - - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ - fun primaryPhoneNumber(primaryPhoneNumber: Optional) = - primaryPhoneNumber(primaryPhoneNumber.orElse(null)) - - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ - fun primaryPhoneNumber(primaryPhoneNumber: JsonField) = apply { - this.primaryPhoneNumber = primaryPhoneNumber - } + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - fun build(): CompanyWithoutId = - CompanyWithoutId( - checkRequired("accounts", accounts).map { it.toImmutable() }, - checkRequired("departments", departments).map { it.toImmutable() }, - checkRequired("ein", ein), - checkRequired("entity", entity), - checkRequired("legalName", legalName), - checkRequired("locations", locations).map { it.toImmutable() }, - checkRequired("primaryEmail", primaryEmail), - checkRequired("primaryPhoneNumber", primaryPhoneNumber), - additionalProperties.toImmutable(), - ) + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** + * Returns an immutable instance of [SandboxCompanyUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accounts() + * .departments() + * .ein() + * .entity() + * .legalName() + * .locations() + * .primaryEmail() + * .primaryPhoneNumber() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SandboxCompanyUpdateParams = + SandboxCompanyUpdateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } - return /* spotless:off */ other is CompanyWithoutId && accounts == other.accounts && departments == other.departments && ein == other.ein && entity == other.entity && legalName == other.legalName && locations == other.locations && primaryEmail == other.primaryEmail && primaryPhoneNumber == other.primaryPhoneNumber && additionalProperties == other.additionalProperties /* spotless:on */ - } + fun _body(): CompanyWithoutId = body - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(accounts, departments, ein, entity, legalName, locations, primaryEmail, primaryPhoneNumber, additionalProperties) } - /* spotless:on */ + override fun _headers(): Headers = additionalHeaders - override fun hashCode(): Int = hashCode + override fun _queryParams(): QueryParams = additionalQueryParams - override fun toString() = - "CompanyWithoutId{accounts=$accounts, departments=$departments, ein=$ein, entity=$entity, legalName=$legalName, locations=$locations, primaryEmail=$primaryEmail, primaryPhoneNumber=$primaryPhoneNumber, additionalProperties=$additionalProperties}" - } + class CompanyWithoutId + private constructor( + private val accounts: JsonField>, + private val departments: JsonField>, + private val ein: JsonField, + private val entity: JsonField, + private val legalName: JsonField, + private val locations: JsonField>, + private val primaryEmail: JsonField, + private val primaryPhoneNumber: JsonField, + private val additionalProperties: MutableMap, + ) { - fun toBuilder() = Builder().from(this) + @JsonCreator + private constructor( + @JsonProperty("accounts") + @ExcludeMissing + accounts: JsonField> = JsonMissing.of(), + @JsonProperty("departments") + @ExcludeMissing + departments: JsonField> = JsonMissing.of(), + @JsonProperty("ein") @ExcludeMissing ein: JsonField = JsonMissing.of(), + @JsonProperty("entity") @ExcludeMissing entity: JsonField = JsonMissing.of(), + @JsonProperty("legal_name") + @ExcludeMissing + legalName: JsonField = JsonMissing.of(), + @JsonProperty("locations") + @ExcludeMissing + locations: JsonField> = JsonMissing.of(), + @JsonProperty("primary_email") + @ExcludeMissing + primaryEmail: JsonField = JsonMissing.of(), + @JsonProperty("primary_phone_number") + @ExcludeMissing + primaryPhoneNumber: JsonField = JsonMissing.of(), + ) : this( + accounts, + departments, + ein, + entity, + legalName, + locations, + primaryEmail, + primaryPhoneNumber, + mutableMapOf(), + ) - companion object { + /** + * An array of bank account objects associated with the payroll/HRIS system. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun accounts(): Optional> = accounts.getOptional("accounts") - @JvmStatic fun builder() = Builder() - } + /** + * The array of company departments. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun departments(): Optional> = departments.getOptional("departments") - /** A builder for [SandboxCompanyUpdateParams]. */ - @NoAutoDetect - class Builder internal constructor() { + /** + * The employer identification number. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun ein(): Optional = ein.getOptional("ein") - private var body: CompanyWithoutId.Builder = CompanyWithoutId.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + /** + * The entity type object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun entity(): Optional = entity.getOptional("entity") - @JvmSynthetic - internal fun from(sandboxCompanyUpdateParams: SandboxCompanyUpdateParams) = apply { - body = sandboxCompanyUpdateParams.body.toBuilder() - additionalHeaders = sandboxCompanyUpdateParams.additionalHeaders.toBuilder() - additionalQueryParams = sandboxCompanyUpdateParams.additionalQueryParams.toBuilder() - } + /** + * The legal name of the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun legalName(): Optional = legalName.getOptional("legal_name") - /** An array of bank account objects associated with the payroll/HRIS system. */ - fun accounts(accounts: List?) = apply { body.accounts(accounts) } + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun locations(): Optional> = locations.getOptional("locations") - /** An array of bank account objects associated with the payroll/HRIS system. */ - fun accounts(accounts: Optional>) = accounts(accounts.orElse(null)) + /** + * The email of the main administrator on the account. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun primaryEmail(): Optional = primaryEmail.getOptional("primary_email") - /** An array of bank account objects associated with the payroll/HRIS system. */ - fun accounts(accounts: JsonField>) = apply { body.accounts(accounts) } + /** + * The phone number of the main administrator on the account. Format: `XXXXXXXXXX` + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun primaryPhoneNumber(): Optional = + primaryPhoneNumber.getOptional("primary_phone_number") - /** An array of bank account objects associated with the payroll/HRIS system. */ - fun addAccount(account: Account) = apply { body.addAccount(account) } + /** + * Returns the raw JSON value of [accounts]. + * + * Unlike [accounts], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("accounts") + @ExcludeMissing + fun _accounts(): JsonField> = accounts - /** The array of company departments. */ - fun departments(departments: List?) = apply { body.departments(departments) } + /** + * Returns the raw JSON value of [departments]. + * + * Unlike [departments], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("departments") + @ExcludeMissing + fun _departments(): JsonField> = departments - /** The array of company departments. */ - fun departments(departments: Optional>) = - departments(departments.orElse(null)) + /** + * Returns the raw JSON value of [ein]. + * + * Unlike [ein], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("ein") @ExcludeMissing fun _ein(): JsonField = ein - /** The array of company departments. */ - fun departments(departments: JsonField>) = apply { - body.departments(departments) - } + /** + * Returns the raw JSON value of [entity]. + * + * Unlike [entity], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("entity") @ExcludeMissing fun _entity(): JsonField = entity - /** The array of company departments. */ - fun addDepartment(department: Department) = apply { body.addDepartment(department) } + /** + * Returns the raw JSON value of [legalName]. + * + * Unlike [legalName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("legal_name") @ExcludeMissing fun _legalName(): JsonField = legalName - /** The employer identification number. */ - fun ein(ein: String?) = apply { body.ein(ein) } + /** + * Returns the raw JSON value of [locations]. + * + * Unlike [locations], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("locations") + @ExcludeMissing + fun _locations(): JsonField> = locations - /** The employer identification number. */ - fun ein(ein: Optional) = ein(ein.orElse(null)) + /** + * Returns the raw JSON value of [primaryEmail]. + * + * Unlike [primaryEmail], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("primary_email") + @ExcludeMissing + fun _primaryEmail(): JsonField = primaryEmail - /** The employer identification number. */ - fun ein(ein: JsonField) = apply { body.ein(ein) } + /** + * Returns the raw JSON value of [primaryPhoneNumber]. + * + * Unlike [primaryPhoneNumber], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("primary_phone_number") + @ExcludeMissing + fun _primaryPhoneNumber(): JsonField = primaryPhoneNumber - /** The entity type object. */ - fun entity(entity: Entity?) = apply { body.entity(entity) } + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } - /** The entity type object. */ - fun entity(entity: Optional) = entity(entity.orElse(null)) + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - /** The entity type object. */ - fun entity(entity: JsonField) = apply { body.entity(entity) } + fun toBuilder() = Builder().from(this) - /** The legal name of the company. */ - fun legalName(legalName: String?) = apply { body.legalName(legalName) } + companion object { - /** The legal name of the company. */ - fun legalName(legalName: Optional) = legalName(legalName.orElse(null)) + /** + * Returns a mutable builder for constructing an instance of [CompanyWithoutId]. + * + * The following fields are required: + * ```java + * .accounts() + * .departments() + * .ein() + * .entity() + * .legalName() + * .locations() + * .primaryEmail() + * .primaryPhoneNumber() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - /** The legal name of the company. */ - fun legalName(legalName: JsonField) = apply { body.legalName(legalName) } + /** A builder for [CompanyWithoutId]. */ + class Builder internal constructor() { - fun locations(locations: List?) = apply { body.locations(locations) } + private var accounts: JsonField>? = null + private var departments: JsonField>? = null + private var ein: JsonField? = null + private var entity: JsonField? = null + private var legalName: JsonField? = null + private var locations: JsonField>? = null + private var primaryEmail: JsonField? = null + private var primaryPhoneNumber: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() - fun locations(locations: Optional>) = locations(locations.orElse(null)) + @JvmSynthetic + internal fun from(companyWithoutId: CompanyWithoutId) = apply { + accounts = companyWithoutId.accounts.map { it.toMutableList() } + departments = companyWithoutId.departments.map { it.toMutableList() } + ein = companyWithoutId.ein + entity = companyWithoutId.entity + legalName = companyWithoutId.legalName + locations = companyWithoutId.locations.map { it.toMutableList() } + primaryEmail = companyWithoutId.primaryEmail + primaryPhoneNumber = companyWithoutId.primaryPhoneNumber + additionalProperties = companyWithoutId.additionalProperties.toMutableMap() + } - fun locations(locations: JsonField>) = apply { body.locations(locations) } + /** An array of bank account objects associated with the payroll/HRIS system. */ + fun accounts(accounts: List?) = accounts(JsonField.ofNullable(accounts)) - fun addLocation(location: Location) = apply { body.addLocation(location) } + /** Alias for calling [Builder.accounts] with `accounts.orElse(null)`. */ + fun accounts(accounts: Optional>) = accounts(accounts.getOrNull()) - /** The email of the main administrator on the account. */ - fun primaryEmail(primaryEmail: String?) = apply { body.primaryEmail(primaryEmail) } + /** + * Sets [Builder.accounts] to an arbitrary JSON value. + * + * You should usually call [Builder.accounts] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun accounts(accounts: JsonField>) = apply { + this.accounts = accounts.map { it.toMutableList() } + } - /** The email of the main administrator on the account. */ - fun primaryEmail(primaryEmail: Optional) = primaryEmail(primaryEmail.orElse(null)) + /** + * Adds a single [Account] to [accounts]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAccount(account: Account) = apply { + accounts = + (accounts ?: JsonField.of(mutableListOf())).also { + checkKnown("accounts", it).add(account) + } + } - /** The email of the main administrator on the account. */ - fun primaryEmail(primaryEmail: JsonField) = apply { - body.primaryEmail(primaryEmail) - } + /** The array of company departments. */ + fun departments(departments: List?) = + departments(JsonField.ofNullable(departments)) - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ - fun primaryPhoneNumber(primaryPhoneNumber: String?) = apply { - body.primaryPhoneNumber(primaryPhoneNumber) - } + /** Alias for calling [Builder.departments] with `departments.orElse(null)`. */ + fun departments(departments: Optional>) = + departments(departments.getOrNull()) - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ - fun primaryPhoneNumber(primaryPhoneNumber: Optional) = - primaryPhoneNumber(primaryPhoneNumber.orElse(null)) + /** + * Sets [Builder.departments] to an arbitrary JSON value. + * + * You should usually call [Builder.departments] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun departments(departments: JsonField>) = apply { + this.departments = departments.map { it.toMutableList() } + } - /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ - fun primaryPhoneNumber(primaryPhoneNumber: JsonField) = apply { - body.primaryPhoneNumber(primaryPhoneNumber) - } + /** + * Adds a single [Department] to [departments]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addDepartment(department: Department) = apply { + departments = + (departments ?: JsonField.of(mutableListOf())).also { + checkKnown("departments", it).add(department) + } + } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } + /** The employer identification number. */ + fun ein(ein: String?) = ein(JsonField.ofNullable(ein)) - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + /** Alias for calling [Builder.ein] with `ein.orElse(null)`. */ + fun ein(ein: Optional) = ein(ein.getOrNull()) + + /** + * Sets [Builder.ein] to an arbitrary JSON value. + * + * You should usually call [Builder.ein] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun ein(ein: JsonField) = apply { this.ein = ein } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } + /** The entity type object. */ + fun entity(entity: Entity?) = entity(JsonField.ofNullable(entity)) - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** Alias for calling [Builder.entity] with `entity.orElse(null)`. */ + fun entity(entity: Optional) = entity(entity.getOrNull()) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** + * Sets [Builder.entity] to an arbitrary JSON value. + * + * You should usually call [Builder.entity] with a well-typed [Entity] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun entity(entity: JsonField) = apply { this.entity = entity } - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** The legal name of the company. */ + fun legalName(legalName: String?) = legalName(JsonField.ofNullable(legalName)) - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Alias for calling [Builder.legalName] with `legalName.orElse(null)`. */ + fun legalName(legalName: Optional) = legalName(legalName.getOrNull()) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** + * Sets [Builder.legalName] to an arbitrary JSON value. + * + * You should usually call [Builder.legalName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun legalName(legalName: JsonField) = apply { this.legalName = legalName } - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + fun locations(locations: List?) = locations(JsonField.ofNullable(locations)) - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.locations] with `locations.orElse(null)`. */ + fun locations(locations: Optional>) = locations(locations.getOrNull()) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** + * Sets [Builder.locations] to an arbitrary JSON value. + * + * You should usually call [Builder.locations] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun locations(locations: JsonField>) = apply { + this.locations = locations.map { it.toMutableList() } + } - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Adds a single [Location] to [locations]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addLocation(location: Location) = apply { + locations = + (locations ?: JsonField.of(mutableListOf())).also { + checkKnown("locations", it).add(location) + } + } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** The email of the main administrator on the account. */ + fun primaryEmail(primaryEmail: String?) = + primaryEmail(JsonField.ofNullable(primaryEmail)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.primaryEmail] with `primaryEmail.orElse(null)`. */ + fun primaryEmail(primaryEmail: Optional) = + primaryEmail(primaryEmail.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.primaryEmail] to an arbitrary JSON value. + * + * You should usually call [Builder.primaryEmail] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun primaryEmail(primaryEmail: JsonField) = apply { + this.primaryEmail = primaryEmail + } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** The phone number of the main administrator on the account. Format: `XXXXXXXXXX` */ + fun primaryPhoneNumber(primaryPhoneNumber: String?) = + primaryPhoneNumber(JsonField.ofNullable(primaryPhoneNumber)) - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + /** + * Alias for calling [Builder.primaryPhoneNumber] with + * `primaryPhoneNumber.orElse(null)`. + */ + fun primaryPhoneNumber(primaryPhoneNumber: Optional) = + primaryPhoneNumber(primaryPhoneNumber.getOrNull()) - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * Sets [Builder.primaryPhoneNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.primaryPhoneNumber] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun primaryPhoneNumber(primaryPhoneNumber: JsonField) = apply { + this.primaryPhoneNumber = primaryPhoneNumber + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + /** + * Returns an immutable instance of [CompanyWithoutId]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .accounts() + * .departments() + * .ein() + * .entity() + * .legalName() + * .locations() + * .primaryEmail() + * .primaryPhoneNumber() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): CompanyWithoutId = + CompanyWithoutId( + checkRequired("accounts", accounts).map { it.toImmutable() }, + checkRequired("departments", departments).map { it.toImmutable() }, + checkRequired("ein", ein), + checkRequired("entity", entity), + checkRequired("legalName", legalName), + checkRequired("locations", locations).map { it.toImmutable() }, + checkRequired("primaryEmail", primaryEmail), + checkRequired("primaryPhoneNumber", primaryPhoneNumber), + additionalProperties.toMutableMap(), + ) } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + private var validated: Boolean = false - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun validate(): CompanyWithoutId = apply { + if (validated) { + return@apply + } + + accounts().ifPresent { it.forEach { it.validate() } } + departments().ifPresent { it.forEach { it?.validate() } } + ein() + entity().ifPresent { it.validate() } + legalName() + locations().ifPresent { it.forEach { it?.validate() } } + primaryEmail() + primaryPhoneNumber() + validated = true } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (accounts.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (departments.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (ein.asKnown().isPresent) 1 else 0) + + (entity.asKnown().getOrNull()?.validity() ?: 0) + + (if (legalName.asKnown().isPresent) 1 else 0) + + (locations.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (primaryEmail.asKnown().isPresent) 1 else 0) + + (if (primaryPhoneNumber.asKnown().isPresent) 1 else 0) - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is CompanyWithoutId && accounts == other.accounts && departments == other.departments && ein == other.ein && entity == other.entity && legalName == other.legalName && locations == other.locations && primaryEmail == other.primaryEmail && primaryPhoneNumber == other.primaryPhoneNumber && additionalProperties == other.additionalProperties /* spotless:on */ } - fun build(): SandboxCompanyUpdateParams = - SandboxCompanyUpdateParams( - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(accounts, departments, ein, entity, legalName, locations, primaryEmail, primaryPhoneNumber, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CompanyWithoutId{accounts=$accounts, departments=$departments, ein=$ein, entity=$entity, legalName=$legalName, locations=$locations, primaryEmail=$primaryEmail, primaryPhoneNumber=$primaryPhoneNumber, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Account - @JsonCreator private constructor( - @JsonProperty("account_name") - @ExcludeMissing - private val accountName: JsonField = JsonMissing.of(), - @JsonProperty("account_number") - @ExcludeMissing - private val accountNumber: JsonField = JsonMissing.of(), - @JsonProperty("account_type") - @ExcludeMissing - private val accountType: JsonField = JsonMissing.of(), - @JsonProperty("institution_name") - @ExcludeMissing - private val institutionName: JsonField = JsonMissing.of(), - @JsonProperty("routing_number") - @ExcludeMissing - private val routingNumber: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val accountName: JsonField, + private val accountNumber: JsonField, + private val accountType: JsonField, + private val institutionName: JsonField, + private val routingNumber: JsonField, + private val additionalProperties: MutableMap, ) { - /** The name of the bank associated in the payroll/HRIS system. */ - fun accountName(): Optional = - Optional.ofNullable(accountName.getNullable("account_name")) + @JsonCreator + private constructor( + @JsonProperty("account_name") + @ExcludeMissing + accountName: JsonField = JsonMissing.of(), + @JsonProperty("account_number") + @ExcludeMissing + accountNumber: JsonField = JsonMissing.of(), + @JsonProperty("account_type") + @ExcludeMissing + accountType: JsonField = JsonMissing.of(), + @JsonProperty("institution_name") + @ExcludeMissing + institutionName: JsonField = JsonMissing.of(), + @JsonProperty("routing_number") + @ExcludeMissing + routingNumber: JsonField = JsonMissing.of(), + ) : this( + accountName, + accountNumber, + accountType, + institutionName, + routingNumber, + mutableMapOf(), + ) + + /** + * The name of the bank associated in the payroll/HRIS system. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun accountName(): Optional = accountName.getOptional("account_name") - /** 10-12 digit number to specify the bank account */ - fun accountNumber(): Optional = - Optional.ofNullable(accountNumber.getNullable("account_number")) + /** + * 10-12 digit number to specify the bank account + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun accountNumber(): Optional = accountNumber.getOptional("account_number") - /** The type of bank account. */ - fun accountType(): Optional = - Optional.ofNullable(accountType.getNullable("account_type")) + /** + * The type of bank account. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun accountType(): Optional = accountType.getOptional("account_type") - /** Name of the banking institution. */ - fun institutionName(): Optional = - Optional.ofNullable(institutionName.getNullable("institution_name")) + /** + * Name of the banking institution. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun institutionName(): Optional = institutionName.getOptional("institution_name") /** * A nine-digit code that's based on the U.S. Bank location where your account was opened. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun routingNumber(): Optional = - Optional.ofNullable(routingNumber.getNullable("routing_number")) + fun routingNumber(): Optional = routingNumber.getOptional("routing_number") - /** The name of the bank associated in the payroll/HRIS system. */ + /** + * Returns the raw JSON value of [accountName]. + * + * Unlike [accountName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("account_name") @ExcludeMissing fun _accountName(): JsonField = accountName - /** 10-12 digit number to specify the bank account */ + /** + * Returns the raw JSON value of [accountNumber]. + * + * Unlike [accountNumber], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("account_number") @ExcludeMissing fun _accountNumber(): JsonField = accountNumber - /** The type of bank account. */ + /** + * Returns the raw JSON value of [accountType]. + * + * Unlike [accountType], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("account_type") @ExcludeMissing fun _accountType(): JsonField = accountType - /** Name of the banking institution. */ + /** + * Returns the raw JSON value of [institutionName]. + * + * Unlike [institutionName], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("institution_name") @ExcludeMissing fun _institutionName(): JsonField = institutionName /** - * A nine-digit code that's based on the U.S. Bank location where your account was opened. + * Returns the raw JSON value of [routingNumber]. + * + * Unlike [routingNumber], this method doesn't throw if the JSON field has an unexpected + * type. */ @JsonProperty("routing_number") @ExcludeMissing fun _routingNumber(): JsonField = routingNumber + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Account = apply { - if (validated) { - return@apply - } - - accountName() - accountNumber() - accountType() - institutionName() - routingNumber() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Account]. */ @JvmStatic fun builder() = Builder() } @@ -766,10 +1194,16 @@ private constructor( /** The name of the bank associated in the payroll/HRIS system. */ fun accountName(accountName: String?) = accountName(JsonField.ofNullable(accountName)) - /** The name of the bank associated in the payroll/HRIS system. */ - fun accountName(accountName: Optional) = accountName(accountName.orElse(null)) + /** Alias for calling [Builder.accountName] with `accountName.orElse(null)`. */ + fun accountName(accountName: Optional) = accountName(accountName.getOrNull()) - /** The name of the bank associated in the payroll/HRIS system. */ + /** + * Sets [Builder.accountName] to an arbitrary JSON value. + * + * You should usually call [Builder.accountName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun accountName(accountName: JsonField) = apply { this.accountName = accountName } @@ -778,11 +1212,17 @@ private constructor( fun accountNumber(accountNumber: String?) = accountNumber(JsonField.ofNullable(accountNumber)) - /** 10-12 digit number to specify the bank account */ + /** Alias for calling [Builder.accountNumber] with `accountNumber.orElse(null)`. */ fun accountNumber(accountNumber: Optional) = - accountNumber(accountNumber.orElse(null)) + accountNumber(accountNumber.getOrNull()) - /** 10-12 digit number to specify the bank account */ + /** + * Sets [Builder.accountNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.accountNumber] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun accountNumber(accountNumber: JsonField) = apply { this.accountNumber = accountNumber } @@ -791,11 +1231,17 @@ private constructor( fun accountType(accountType: AccountType?) = accountType(JsonField.ofNullable(accountType)) - /** The type of bank account. */ + /** Alias for calling [Builder.accountType] with `accountType.orElse(null)`. */ fun accountType(accountType: Optional) = - accountType(accountType.orElse(null)) + accountType(accountType.getOrNull()) - /** The type of bank account. */ + /** + * Sets [Builder.accountType] to an arbitrary JSON value. + * + * You should usually call [Builder.accountType] with a well-typed [AccountType] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun accountType(accountType: JsonField) = apply { this.accountType = accountType } @@ -804,11 +1250,17 @@ private constructor( fun institutionName(institutionName: String?) = institutionName(JsonField.ofNullable(institutionName)) - /** Name of the banking institution. */ + /** Alias for calling [Builder.institutionName] with `institutionName.orElse(null)`. */ fun institutionName(institutionName: Optional) = - institutionName(institutionName.orElse(null)) + institutionName(institutionName.getOrNull()) - /** Name of the banking institution. */ + /** + * Sets [Builder.institutionName] to an arbitrary JSON value. + * + * You should usually call [Builder.institutionName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun institutionName(institutionName: JsonField) = apply { this.institutionName = institutionName } @@ -820,16 +1272,16 @@ private constructor( fun routingNumber(routingNumber: String?) = routingNumber(JsonField.ofNullable(routingNumber)) - /** - * A nine-digit code that's based on the U.S. Bank location where your account was - * opened. - */ + /** Alias for calling [Builder.routingNumber] with `routingNumber.orElse(null)`. */ fun routingNumber(routingNumber: Optional) = - routingNumber(routingNumber.orElse(null)) + routingNumber(routingNumber.getOrNull()) /** - * A nine-digit code that's based on the U.S. Bank location where your account was - * opened. + * Sets [Builder.routingNumber] to an arbitrary JSON value. + * + * You should usually call [Builder.routingNumber] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun routingNumber(routingNumber: JsonField) = apply { this.routingNumber = routingNumber @@ -854,6 +1306,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Account]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Account = Account( accountName, @@ -861,10 +1318,47 @@ private constructor( accountType, institutionName, routingNumber, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Account = apply { + if (validated) { + return@apply + } + + accountName() + accountNumber() + accountType().ifPresent { it.validate() } + institutionName() + routingNumber() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (accountName.asKnown().isPresent) 1 else 0) + + (if (accountNumber.asKnown().isPresent) 1 else 0) + + (accountType.asKnown().getOrNull()?.validity() ?: 0) + + (if (institutionName.asKnown().isPresent) 1 else 0) + + (if (routingNumber.asKnown().isPresent) 1 else 0) + /** The type of bank account. */ class AccountType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -957,6 +1451,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): AccountType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -988,52 +1509,64 @@ private constructor( "Account{accountName=$accountName, accountNumber=$accountNumber, accountType=$accountType, institutionName=$institutionName, routingNumber=$routingNumber, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Department - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("parent") - @ExcludeMissing - private val parent: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val parent: JsonField, + private val additionalProperties: MutableMap, ) { - /** The department name. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("parent") @ExcludeMissing parent: JsonField = JsonMissing.of(), + ) : this(name, parent, mutableMapOf()) - /** The parent department, if present. */ - fun parent(): Optional = Optional.ofNullable(parent.getNullable("parent")) + /** + * The department name. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * The parent department, if present. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun parent(): Optional = parent.getOptional("parent") - /** The department name. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** The parent department, if present. */ + /** + * Returns the raw JSON value of [parent]. + * + * Unlike [parent], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("parent") @ExcludeMissing fun _parent(): JsonField = parent + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Department = apply { - if (validated) { - return@apply - } - - name() - parent().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Department]. */ @JvmStatic fun builder() = Builder() } @@ -1054,19 +1587,31 @@ private constructor( /** The department name. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The department name. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The department name. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } /** The parent department, if present. */ fun parent(parent: Parent?) = parent(JsonField.ofNullable(parent)) - /** The parent department, if present. */ - fun parent(parent: Optional) = parent(parent.orElse(null)) + /** Alias for calling [Builder.parent] with `parent.orElse(null)`. */ + fun parent(parent: Optional) = parent(parent.getOrNull()) - /** The parent department, if present. */ + /** + * Sets [Builder.parent] to an arbitrary JSON value. + * + * You should usually call [Builder.parent] with a well-typed [Parent] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun parent(parent: JsonField) = apply { this.parent = parent } fun additionalProperties(additionalProperties: Map) = apply { @@ -1088,46 +1633,87 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Department = Department(name, parent, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Department]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Department = Department(name, parent, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Department = apply { + if (validated) { + return@apply + } + + name() + parent().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (name.asKnown().isPresent) 1 else 0) + + (parent.asKnown().getOrNull()?.validity() ?: 0) + /** The parent department, if present. */ - @NoAutoDetect class Parent - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - /** The parent department's name. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) + + /** + * The parent department's name. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** The parent department's name. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Parent = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Parent]. */ @JvmStatic fun builder() = Builder() } @@ -1146,10 +1732,16 @@ private constructor( /** The parent department's name. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The parent department's name. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The parent department's name. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = apply { @@ -1174,9 +1766,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Parent = Parent(name, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Parent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Parent = Parent(name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Parent = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1214,50 +1838,64 @@ private constructor( } /** The entity type object. */ - @NoAutoDetect class Entity - @JsonCreator private constructor( - @JsonProperty("subtype") - @ExcludeMissing - private val subtype: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val subtype: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The tax payer subtype of the company. */ - fun subtype(): Optional = Optional.ofNullable(subtype.getNullable("subtype")) + @JsonCreator + private constructor( + @JsonProperty("subtype") @ExcludeMissing subtype: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(subtype, type, mutableMapOf()) - /** The tax payer type of the company. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The tax payer subtype of the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun subtype(): Optional = subtype.getOptional("subtype") - /** The tax payer subtype of the company. */ + /** + * The tax payer type of the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [subtype]. + * + * Unlike [subtype], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype - /** The tax payer type of the company. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Entity = apply { - if (validated) { - return@apply - } - - subtype() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Entity]. */ @JvmStatic fun builder() = Builder() } @@ -1278,19 +1916,31 @@ private constructor( /** The tax payer subtype of the company. */ fun subtype(subtype: Subtype?) = subtype(JsonField.ofNullable(subtype)) - /** The tax payer subtype of the company. */ - fun subtype(subtype: Optional) = subtype(subtype.orElse(null)) + /** Alias for calling [Builder.subtype] with `subtype.orElse(null)`. */ + fun subtype(subtype: Optional) = subtype(subtype.getOrNull()) - /** The tax payer subtype of the company. */ + /** + * Sets [Builder.subtype] to an arbitrary JSON value. + * + * You should usually call [Builder.subtype] with a well-typed [Subtype] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun subtype(subtype: JsonField) = apply { this.subtype = subtype } /** The tax payer type of the company. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** The tax payer type of the company. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** The tax payer type of the company. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -1312,9 +1962,45 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Entity = Entity(subtype, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Entity]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Entity = Entity(subtype, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Entity = apply { + if (validated) { + return@apply + } + + subtype().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (subtype.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + /** The tax payer subtype of the company. */ class Subtype @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1412,6 +2098,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Subtype = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1543,6 +2256,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxConnectionAccountCreateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxConnectionAccountCreateParams.kt index e450d723..18a7ccc0 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxConnectionAccountCreateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxConnectionAccountCreateParams.kt @@ -11,16 +11,17 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Create a new account for an existing connection (company/provider pair) */ class SandboxConnectionAccountCreateParams @@ -30,29 +31,61 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun companyId(): String = body.companyId() - /** The provider associated with the `access_token` */ + /** + * The provider associated with the `access_token` + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun providerId(): String = body.providerId() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun authenticationType(): Optional = body.authenticationType() /** * Optional, defaults to Organization products (`company`, `directory`, `employment`, * `individual`) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ fun products(): Optional> = body.products() + /** + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. + */ fun _companyId(): JsonField = body._companyId() - /** The provider associated with the `access_token` */ + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ fun _providerId(): JsonField = body._providerId() + /** + * Returns the raw JSON value of [authenticationType]. + * + * Unlike [authenticationType], this method doesn't throw if the JSON field has an unexpected + * type. + */ fun _authenticationType(): JsonField = body._authenticationType() /** - * Optional, defaults to Organization products (`company`, `directory`, `employment`, - * `individual`) + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. */ fun _products(): JsonField> = body._products() @@ -62,213 +95,24 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("company_id") - @ExcludeMissing - private val companyId: JsonField = JsonMissing.of(), - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonProperty("authentication_type") - @ExcludeMissing - private val authenticationType: JsonField = JsonMissing.of(), - @JsonProperty("products") - @ExcludeMissing - private val products: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun companyId(): String = companyId.getRequired("company_id") - - /** The provider associated with the `access_token` */ - fun providerId(): String = providerId.getRequired("provider_id") - - fun authenticationType(): Optional = - Optional.ofNullable(authenticationType.getNullable("authentication_type")) - - /** - * Optional, defaults to Organization products (`company`, `directory`, `employment`, - * `individual`) - */ - fun products(): Optional> = - Optional.ofNullable(products.getNullable("products")) - - @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId - - /** The provider associated with the `access_token` */ - @JsonProperty("provider_id") - @ExcludeMissing - fun _providerId(): JsonField = providerId - - @JsonProperty("authentication_type") - @ExcludeMissing - fun _authenticationType(): JsonField = authenticationType - - /** - * Optional, defaults to Organization products (`company`, `directory`, `employment`, - * `individual`) - */ - @JsonProperty("products") - @ExcludeMissing - fun _products(): JsonField> = products - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - companyId() - providerId() - authenticationType() - products() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var companyId: JsonField? = null - private var providerId: JsonField? = null - private var authenticationType: JsonField = JsonMissing.of() - private var products: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - companyId = body.companyId - providerId = body.providerId - authenticationType = body.authenticationType - products = body.products.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - fun companyId(companyId: String) = companyId(JsonField.of(companyId)) - - fun companyId(companyId: JsonField) = apply { this.companyId = companyId } - - /** The provider associated with the `access_token` */ - fun providerId(providerId: String) = providerId(JsonField.of(providerId)) - - /** The provider associated with the `access_token` */ - fun providerId(providerId: JsonField) = apply { this.providerId = providerId } - - fun authenticationType(authenticationType: AuthenticationType) = - authenticationType(JsonField.of(authenticationType)) - - fun authenticationType(authenticationType: JsonField) = apply { - this.authenticationType = authenticationType - } - - /** - * Optional, defaults to Organization products (`company`, `directory`, `employment`, - * `individual`) - */ - fun products(products: List) = products(JsonField.of(products)) - - /** - * Optional, defaults to Organization products (`company`, `directory`, `employment`, - * `individual`) - */ - fun products(products: JsonField>) = apply { - this.products = products.map { it.toMutableList() } - } - - /** - * Optional, defaults to Organization products (`company`, `directory`, `employment`, - * `individual`) - */ - fun addProduct(product: String) = apply { - products = - (products ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(product) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = - Body( - checkRequired("companyId", companyId), - checkRequired("providerId", providerId), - authenticationType, - (products ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && companyId == other.companyId && providerId == other.providerId && authenticationType == other.authenticationType && products == other.products && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(companyId, providerId, authenticationType, products, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{companyId=$companyId, providerId=$providerId, authenticationType=$authenticationType, products=$products, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SandboxConnectionAccountCreateParams]. + * + * The following fields are required: + * ```java + * .companyId() + * .providerId() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [SandboxConnectionAccountCreateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -285,20 +129,52 @@ private constructor( sandboxConnectionAccountCreateParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [companyId] + * - [providerId] + * - [authenticationType] + * - [products] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + fun companyId(companyId: String) = apply { body.companyId(companyId) } + /** + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun companyId(companyId: JsonField) = apply { body.companyId(companyId) } /** The provider associated with the `access_token` */ fun providerId(providerId: String) = apply { body.providerId(providerId) } - /** The provider associated with the `access_token` */ + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun providerId(providerId: JsonField) = apply { body.providerId(providerId) } fun authenticationType(authenticationType: AuthenticationType) = apply { body.authenticationType(authenticationType) } + /** + * Sets [Builder.authenticationType] to an arbitrary JSON value. + * + * You should usually call [Builder.authenticationType] with a well-typed + * [AuthenticationType] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun authenticationType(authenticationType: JsonField) = apply { body.authenticationType(authenticationType) } @@ -310,14 +186,18 @@ private constructor( fun products(products: List) = apply { body.products(products) } /** - * Optional, defaults to Organization products (`company`, `directory`, `employment`, - * `individual`) + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun products(products: JsonField>) = apply { body.products(products) } /** - * Optional, defaults to Organization products (`company`, `directory`, `employment`, - * `individual`) + * Adds a single [String] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. */ fun addProduct(product: String) = apply { body.addProduct(product) } @@ -438,6 +318,19 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [SandboxConnectionAccountCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .companyId() + * .providerId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): SandboxConnectionAccountCreateParams = SandboxConnectionAccountCreateParams( body.build(), @@ -446,6 +339,307 @@ private constructor( ) } + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val companyId: JsonField, + private val providerId: JsonField, + private val authenticationType: JsonField, + private val products: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("company_id") + @ExcludeMissing + companyId: JsonField = JsonMissing.of(), + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + @JsonProperty("authentication_type") + @ExcludeMissing + authenticationType: JsonField = JsonMissing.of(), + @JsonProperty("products") + @ExcludeMissing + products: JsonField> = JsonMissing.of(), + ) : this(companyId, providerId, authenticationType, products, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun companyId(): String = companyId.getRequired("company_id") + + /** + * The provider associated with the `access_token` + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun providerId(): String = providerId.getRequired("provider_id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun authenticationType(): Optional = + authenticationType.getOptional("authentication_type") + + /** + * Optional, defaults to Organization products (`company`, `directory`, `employment`, + * `individual`) + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun products(): Optional> = products.getOptional("products") + + /** + * Returns the raw JSON value of [companyId]. + * + * Unlike [companyId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("company_id") @ExcludeMissing fun _companyId(): JsonField = companyId + + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("provider_id") + @ExcludeMissing + fun _providerId(): JsonField = providerId + + /** + * Returns the raw JSON value of [authenticationType]. + * + * Unlike [authenticationType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("authentication_type") + @ExcludeMissing + fun _authenticationType(): JsonField = authenticationType + + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("products") + @ExcludeMissing + fun _products(): JsonField> = products + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .companyId() + * .providerId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var companyId: JsonField? = null + private var providerId: JsonField? = null + private var authenticationType: JsonField = JsonMissing.of() + private var products: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + companyId = body.companyId + providerId = body.providerId + authenticationType = body.authenticationType + products = body.products.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + fun companyId(companyId: String) = companyId(JsonField.of(companyId)) + + /** + * Sets [Builder.companyId] to an arbitrary JSON value. + * + * You should usually call [Builder.companyId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun companyId(companyId: JsonField) = apply { this.companyId = companyId } + + /** The provider associated with the `access_token` */ + fun providerId(providerId: String) = providerId(JsonField.of(providerId)) + + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun providerId(providerId: JsonField) = apply { this.providerId = providerId } + + fun authenticationType(authenticationType: AuthenticationType) = + authenticationType(JsonField.of(authenticationType)) + + /** + * Sets [Builder.authenticationType] to an arbitrary JSON value. + * + * You should usually call [Builder.authenticationType] with a well-typed + * [AuthenticationType] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun authenticationType(authenticationType: JsonField) = apply { + this.authenticationType = authenticationType + } + + /** + * Optional, defaults to Organization products (`company`, `directory`, `employment`, + * `individual`) + */ + fun products(products: List) = products(JsonField.of(products)) + + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun products(products: JsonField>) = apply { + this.products = products.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addProduct(product: String) = apply { + products = + (products ?: JsonField.of(mutableListOf())).also { + checkKnown("products", it).add(product) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .companyId() + * .providerId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("companyId", companyId), + checkRequired("providerId", providerId), + authenticationType, + (products ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + companyId() + providerId() + authenticationType().ifPresent { it.validate() } + products() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (companyId.asKnown().isPresent) 1 else 0) + + (if (providerId.asKnown().isPresent) 1 else 0) + + (authenticationType.asKnown().getOrNull()?.validity() ?: 0) + + (products.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && companyId == other.companyId && providerId == other.providerId && authenticationType == other.authenticationType && products == other.products && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(companyId, providerId, authenticationType, products, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{companyId=$companyId, providerId=$providerId, authenticationType=$authenticationType, products=$products, additionalProperties=$additionalProperties}" + } + class AuthenticationType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -547,6 +741,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): AuthenticationType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxConnectionAccountUpdateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxConnectionAccountUpdateParams.kt index 521e6d18..815ad542 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxConnectionAccountUpdateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxConnectionAccountUpdateParams.kt @@ -10,14 +10,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** * Update an existing sandbox account. Change the connection status to understand how the Finch API @@ -30,8 +30,18 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun connectionStatus(): Optional = body.connectionStatus() + /** + * Returns the raw JSON value of [connectionStatus]. + * + * Unlike [connectionStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ fun _connectionStatus(): JsonField = body._connectionStatus() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -40,122 +50,20 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("connection_status") - @ExcludeMissing - private val connectionStatus: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun connectionStatus(): Optional = - Optional.ofNullable(connectionStatus.getNullable("connection_status")) - - @JsonProperty("connection_status") - @ExcludeMissing - fun _connectionStatus(): JsonField = connectionStatus - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - connectionStatus() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var connectionStatus: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - connectionStatus = body.connectionStatus - additionalProperties = body.additionalProperties.toMutableMap() - } - - fun connectionStatus(connectionStatus: ConnectionStatusType) = - connectionStatus(JsonField.of(connectionStatus)) - - fun connectionStatus(connectionStatus: JsonField) = apply { - this.connectionStatus = connectionStatus - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = Body(connectionStatus, additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && connectionStatus == other.connectionStatus && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(connectionStatus, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{connectionStatus=$connectionStatus, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): SandboxConnectionAccountUpdateParams = builder().build() + /** + * Returns a mutable builder for constructing an instance of + * [SandboxConnectionAccountUpdateParams]. + */ @JvmStatic fun builder() = Builder() } /** A builder for [SandboxConnectionAccountUpdateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -172,10 +80,26 @@ private constructor( sandboxConnectionAccountUpdateParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [connectionStatus] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + fun connectionStatus(connectionStatus: ConnectionStatusType) = apply { body.connectionStatus(connectionStatus) } + /** + * Sets [Builder.connectionStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionStatus] with a well-typed + * [ConnectionStatusType] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ fun connectionStatus(connectionStatus: JsonField) = apply { body.connectionStatus(connectionStatus) } @@ -297,6 +221,11 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [SandboxConnectionAccountUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SandboxConnectionAccountUpdateParams = SandboxConnectionAccountUpdateParams( body.build(), @@ -305,6 +234,159 @@ private constructor( ) } + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val connectionStatus: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("connection_status") + @ExcludeMissing + connectionStatus: JsonField = JsonMissing.of() + ) : this(connectionStatus, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun connectionStatus(): Optional = + connectionStatus.getOptional("connection_status") + + /** + * Returns the raw JSON value of [connectionStatus]. + * + * Unlike [connectionStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("connection_status") + @ExcludeMissing + fun _connectionStatus(): JsonField = connectionStatus + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var connectionStatus: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + connectionStatus = body.connectionStatus + additionalProperties = body.additionalProperties.toMutableMap() + } + + fun connectionStatus(connectionStatus: ConnectionStatusType) = + connectionStatus(JsonField.of(connectionStatus)) + + /** + * Sets [Builder.connectionStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.connectionStatus] with a well-typed + * [ConnectionStatusType] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun connectionStatus(connectionStatus: JsonField) = apply { + this.connectionStatus = connectionStatus + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = Body(connectionStatus, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + connectionStatus().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (connectionStatus.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && connectionStatus == other.connectionStatus && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(connectionStatus, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{connectionStatus=$connectionStatus, additionalProperties=$additionalProperties}" + } + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxConnectionCreateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxConnectionCreateParams.kt index cf3c8589..3b877625 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxConnectionCreateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxConnectionCreateParams.kt @@ -11,16 +11,17 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Create a new connection (new company/provider pair) with a new account */ class SandboxConnectionCreateParams @@ -30,32 +31,63 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { - /** The provider associated with the connection */ + /** + * The provider associated with the connection + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun providerId(): String = body.providerId() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun authenticationType(): Optional = body.authenticationType() /** * Optional: the size of the employer to be created with this connection. Defaults to 20. Note * that if this is higher than 100, historical payroll data will not be generated, and instead * only one pay period will be created. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ fun employeeSize(): Optional = body.employeeSize() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun products(): Optional> = body.products() - /** The provider associated with the connection */ + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ fun _providerId(): JsonField = body._providerId() + /** + * Returns the raw JSON value of [authenticationType]. + * + * Unlike [authenticationType], this method doesn't throw if the JSON field has an unexpected + * type. + */ fun _authenticationType(): JsonField = body._authenticationType() /** - * Optional: the size of the employer to be created with this connection. Defaults to 20. Note - * that if this is higher than 100, historical payroll data will not be generated, and instead - * only one pay period will be created. + * Returns the raw JSON value of [employeeSize]. + * + * Unlike [employeeSize], this method doesn't throw if the JSON field has an unexpected type. */ fun _employeeSize(): JsonField = body._employeeSize() + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ fun _products(): JsonField> = body._products() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -64,218 +96,23 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("provider_id") - @ExcludeMissing - private val providerId: JsonField = JsonMissing.of(), - @JsonProperty("authentication_type") - @ExcludeMissing - private val authenticationType: JsonField = JsonMissing.of(), - @JsonProperty("employee_size") - @ExcludeMissing - private val employeeSize: JsonField = JsonMissing.of(), - @JsonProperty("products") - @ExcludeMissing - private val products: JsonField> = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** The provider associated with the connection */ - fun providerId(): String = providerId.getRequired("provider_id") - - fun authenticationType(): Optional = - Optional.ofNullable(authenticationType.getNullable("authentication_type")) - - /** - * Optional: the size of the employer to be created with this connection. Defaults to 20. - * Note that if this is higher than 100, historical payroll data will not be generated, and - * instead only one pay period will be created. - */ - fun employeeSize(): Optional = - Optional.ofNullable(employeeSize.getNullable("employee_size")) - - fun products(): Optional> = - Optional.ofNullable(products.getNullable("products")) - - /** The provider associated with the connection */ - @JsonProperty("provider_id") - @ExcludeMissing - fun _providerId(): JsonField = providerId - - @JsonProperty("authentication_type") - @ExcludeMissing - fun _authenticationType(): JsonField = authenticationType - - /** - * Optional: the size of the employer to be created with this connection. Defaults to 20. - * Note that if this is higher than 100, historical payroll data will not be generated, and - * instead only one pay period will be created. - */ - @JsonProperty("employee_size") - @ExcludeMissing - fun _employeeSize(): JsonField = employeeSize - - @JsonProperty("products") - @ExcludeMissing - fun _products(): JsonField> = products - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - providerId() - authenticationType() - employeeSize() - products() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var providerId: JsonField? = null - private var authenticationType: JsonField = JsonMissing.of() - private var employeeSize: JsonField = JsonMissing.of() - private var products: JsonField>? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - providerId = body.providerId - authenticationType = body.authenticationType - employeeSize = body.employeeSize - products = body.products.map { it.toMutableList() } - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** The provider associated with the connection */ - fun providerId(providerId: String) = providerId(JsonField.of(providerId)) - - /** The provider associated with the connection */ - fun providerId(providerId: JsonField) = apply { this.providerId = providerId } - - fun authenticationType(authenticationType: AuthenticationType) = - authenticationType(JsonField.of(authenticationType)) - - fun authenticationType(authenticationType: JsonField) = apply { - this.authenticationType = authenticationType - } - - /** - * Optional: the size of the employer to be created with this connection. Defaults - * to 20. Note that if this is higher than 100, historical payroll data will not be - * generated, and instead only one pay period will be created. - */ - fun employeeSize(employeeSize: Long) = employeeSize(JsonField.of(employeeSize)) - - /** - * Optional: the size of the employer to be created with this connection. Defaults - * to 20. Note that if this is higher than 100, historical payroll data will not be - * generated, and instead only one pay period will be created. - */ - fun employeeSize(employeeSize: JsonField) = apply { - this.employeeSize = employeeSize - } - - fun products(products: List) = products(JsonField.of(products)) - - fun products(products: JsonField>) = apply { - this.products = products.map { it.toMutableList() } - } - - fun addProduct(product: String) = apply { - products = - (products ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(product) - } - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = - Body( - checkRequired("providerId", providerId), - authenticationType, - employeeSize, - (products ?: JsonMissing.of()).map { it.toImmutable() }, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && providerId == other.providerId && authenticationType == other.authenticationType && employeeSize == other.employeeSize && products == other.products && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(providerId, authenticationType, employeeSize, products, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{providerId=$providerId, authenticationType=$authenticationType, employeeSize=$employeeSize, products=$products, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SandboxConnectionCreateParams]. + * + * The following fields are required: + * ```java + * .providerId() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [SandboxConnectionCreateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -289,16 +126,41 @@ private constructor( additionalQueryParams = sandboxConnectionCreateParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [providerId] + * - [authenticationType] + * - [employeeSize] + * - [products] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** The provider associated with the connection */ fun providerId(providerId: String) = apply { body.providerId(providerId) } - /** The provider associated with the connection */ + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun providerId(providerId: JsonField) = apply { body.providerId(providerId) } fun authenticationType(authenticationType: AuthenticationType) = apply { body.authenticationType(authenticationType) } + /** + * Sets [Builder.authenticationType] to an arbitrary JSON value. + * + * You should usually call [Builder.authenticationType] with a well-typed + * [AuthenticationType] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun authenticationType(authenticationType: JsonField) = apply { body.authenticationType(authenticationType) } @@ -311,16 +173,30 @@ private constructor( fun employeeSize(employeeSize: Long) = apply { body.employeeSize(employeeSize) } /** - * Optional: the size of the employer to be created with this connection. Defaults to 20. - * Note that if this is higher than 100, historical payroll data will not be generated, and - * instead only one pay period will be created. + * Sets [Builder.employeeSize] to an arbitrary JSON value. + * + * You should usually call [Builder.employeeSize] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ fun employeeSize(employeeSize: JsonField) = apply { body.employeeSize(employeeSize) } fun products(products: List) = apply { body.products(products) } + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun products(products: JsonField>) = apply { body.products(products) } + /** + * Adds a single [String] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addProduct(product: String) = apply { body.addProduct(product) } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { @@ -440,6 +316,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [SandboxConnectionCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .providerId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): SandboxConnectionCreateParams = SandboxConnectionCreateParams( body.build(), @@ -448,6 +336,312 @@ private constructor( ) } + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val providerId: JsonField, + private val authenticationType: JsonField, + private val employeeSize: JsonField, + private val products: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("provider_id") + @ExcludeMissing + providerId: JsonField = JsonMissing.of(), + @JsonProperty("authentication_type") + @ExcludeMissing + authenticationType: JsonField = JsonMissing.of(), + @JsonProperty("employee_size") + @ExcludeMissing + employeeSize: JsonField = JsonMissing.of(), + @JsonProperty("products") + @ExcludeMissing + products: JsonField> = JsonMissing.of(), + ) : this(providerId, authenticationType, employeeSize, products, mutableMapOf()) + + /** + * The provider associated with the connection + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun providerId(): String = providerId.getRequired("provider_id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun authenticationType(): Optional = + authenticationType.getOptional("authentication_type") + + /** + * Optional: the size of the employer to be created with this connection. Defaults to 20. + * Note that if this is higher than 100, historical payroll data will not be generated, and + * instead only one pay period will be created. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun employeeSize(): Optional = employeeSize.getOptional("employee_size") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun products(): Optional> = products.getOptional("products") + + /** + * Returns the raw JSON value of [providerId]. + * + * Unlike [providerId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("provider_id") + @ExcludeMissing + fun _providerId(): JsonField = providerId + + /** + * Returns the raw JSON value of [authenticationType]. + * + * Unlike [authenticationType], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("authentication_type") + @ExcludeMissing + fun _authenticationType(): JsonField = authenticationType + + /** + * Returns the raw JSON value of [employeeSize]. + * + * Unlike [employeeSize], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("employee_size") + @ExcludeMissing + fun _employeeSize(): JsonField = employeeSize + + /** + * Returns the raw JSON value of [products]. + * + * Unlike [products], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("products") + @ExcludeMissing + fun _products(): JsonField> = products + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .providerId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var providerId: JsonField? = null + private var authenticationType: JsonField = JsonMissing.of() + private var employeeSize: JsonField = JsonMissing.of() + private var products: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + providerId = body.providerId + authenticationType = body.authenticationType + employeeSize = body.employeeSize + products = body.products.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The provider associated with the connection */ + fun providerId(providerId: String) = providerId(JsonField.of(providerId)) + + /** + * Sets [Builder.providerId] to an arbitrary JSON value. + * + * You should usually call [Builder.providerId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun providerId(providerId: JsonField) = apply { this.providerId = providerId } + + fun authenticationType(authenticationType: AuthenticationType) = + authenticationType(JsonField.of(authenticationType)) + + /** + * Sets [Builder.authenticationType] to an arbitrary JSON value. + * + * You should usually call [Builder.authenticationType] with a well-typed + * [AuthenticationType] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun authenticationType(authenticationType: JsonField) = apply { + this.authenticationType = authenticationType + } + + /** + * Optional: the size of the employer to be created with this connection. Defaults + * to 20. Note that if this is higher than 100, historical payroll data will not be + * generated, and instead only one pay period will be created. + */ + fun employeeSize(employeeSize: Long) = employeeSize(JsonField.of(employeeSize)) + + /** + * Sets [Builder.employeeSize] to an arbitrary JSON value. + * + * You should usually call [Builder.employeeSize] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun employeeSize(employeeSize: JsonField) = apply { + this.employeeSize = employeeSize + } + + fun products(products: List) = products(JsonField.of(products)) + + /** + * Sets [Builder.products] to an arbitrary JSON value. + * + * You should usually call [Builder.products] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun products(products: JsonField>) = apply { + this.products = products.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [products]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addProduct(product: String) = apply { + products = + (products ?: JsonField.of(mutableListOf())).also { + checkKnown("products", it).add(product) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .providerId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("providerId", providerId), + authenticationType, + employeeSize, + (products ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + providerId() + authenticationType().ifPresent { it.validate() } + employeeSize() + products() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (providerId.asKnown().isPresent) 1 else 0) + + (authenticationType.asKnown().getOrNull()?.validity() ?: 0) + + (if (employeeSize.asKnown().isPresent) 1 else 0) + + (products.asKnown().getOrNull()?.size ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && providerId == other.providerId && authenticationType == other.authenticationType && employeeSize == other.employeeSize && products == other.products && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(providerId, authenticationType, employeeSize, products, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{providerId=$providerId, authenticationType=$authenticationType, employeeSize=$employeeSize, products=$products, additionalProperties=$additionalProperties}" + } + class AuthenticationType @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -549,6 +743,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): AuthenticationType = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxDirectoryCreateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxDirectoryCreateParams.kt index 3bca9b07..e13ee7ac 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxDirectoryCreateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxDirectoryCreateParams.kt @@ -11,15 +11,16 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Add new individuals to a sandbox company */ class SandboxDirectoryCreateParams @@ -39,347 +40,645 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic - internal fun _body(): Optional> = Optional.ofNullable(body) + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): SandboxDirectoryCreateParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of [SandboxDirectoryCreateParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SandboxDirectoryCreateParams]. */ + class Builder internal constructor() { + + private var body: MutableList? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(sandboxDirectoryCreateParams: SandboxDirectoryCreateParams) = apply { + body = sandboxDirectoryCreateParams.body?.toMutableList() + additionalHeaders = sandboxDirectoryCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = sandboxDirectoryCreateParams.additionalQueryParams.toBuilder() + } + + /** + * Array of individuals to create. Takes all combined fields from `/individual` and + * `/employment` endpoints. All fields are optional. + */ + fun body(body: List?) = apply { this.body = body?.toMutableList() } + + /** Alias for calling [Builder.body] with `body.orElse(null)`. */ + fun body(body: Optional>) = body(body.getOrNull()) + + /** + * Adds a single [IndividualOrEmployment] to [Builder.body]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addBody(body: IndividualOrEmployment) = apply { + this.body = (this.body ?: mutableListOf()).apply { add(body) } + } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [SandboxDirectoryCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): SandboxDirectoryCreateParams = + SandboxDirectoryCreateParams( + body?.toImmutable(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Optional> = Optional.ofNullable(body) override fun _headers(): Headers = additionalHeaders override fun _queryParams(): QueryParams = additionalQueryParams - @NoAutoDetect class IndividualOrEmployment @JsonCreator private constructor( - @JsonProperty("class_code") - @ExcludeMissing - private val classCode: JsonField = JsonMissing.of(), + @JsonProperty("class_code") @ExcludeMissing private val classCode: JsonField, @JsonProperty("custom_fields") @ExcludeMissing - private val customFields: JsonField> = JsonMissing.of(), - @JsonProperty("department") - @ExcludeMissing - private val department: JsonField = JsonMissing.of(), - @JsonProperty("dob") @ExcludeMissing private val dob: JsonField = JsonMissing.of(), - @JsonProperty("emails") - @ExcludeMissing - private val emails: JsonField> = JsonMissing.of(), - @JsonProperty("employment") - @ExcludeMissing - private val employment: JsonField = JsonMissing.of(), + private val customFields: JsonField>, + @JsonProperty("department") @ExcludeMissing private val department: JsonField, + @JsonProperty("dob") @ExcludeMissing private val dob: JsonField, + @JsonProperty("emails") @ExcludeMissing private val emails: JsonField>, + @JsonProperty("employment") @ExcludeMissing private val employment: JsonField, @JsonProperty("employment_status") @ExcludeMissing - private val employmentStatus: JsonField = JsonMissing.of(), - @JsonProperty("encrypted_ssn") - @ExcludeMissing - private val encryptedSsn: JsonField = JsonMissing.of(), - @JsonProperty("end_date") - @ExcludeMissing - private val endDate: JsonField = JsonMissing.of(), - @JsonProperty("ethnicity") - @ExcludeMissing - private val ethnicity: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("gender") - @ExcludeMissing - private val gender: JsonField = JsonMissing.of(), - @JsonProperty("income") - @ExcludeMissing - private val income: JsonField = JsonMissing.of(), + private val employmentStatus: JsonField, + @JsonProperty("encrypted_ssn") @ExcludeMissing private val encryptedSsn: JsonField, + @JsonProperty("end_date") @ExcludeMissing private val endDate: JsonField, + @JsonProperty("ethnicity") @ExcludeMissing private val ethnicity: JsonField, + @JsonProperty("first_name") @ExcludeMissing private val firstName: JsonField, + @JsonProperty("gender") @ExcludeMissing private val gender: JsonField, + @JsonProperty("income") @ExcludeMissing private val income: JsonField, @JsonProperty("income_history") @ExcludeMissing - private val incomeHistory: JsonField> = JsonMissing.of(), - @JsonProperty("is_active") - @ExcludeMissing - private val isActive: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), + private val incomeHistory: JsonField>, + @JsonProperty("is_active") @ExcludeMissing private val isActive: JsonField, + @JsonProperty("last_name") @ExcludeMissing private val lastName: JsonField, @JsonProperty("latest_rehire_date") @ExcludeMissing - private val latestRehireDate: JsonField = JsonMissing.of(), - @JsonProperty("location") - @ExcludeMissing - private val location: JsonField = JsonMissing.of(), - @JsonProperty("manager") - @ExcludeMissing - private val manager: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), + private val latestRehireDate: JsonField, + @JsonProperty("location") @ExcludeMissing private val location: JsonField, + @JsonProperty("manager") @ExcludeMissing private val manager: JsonField, + @JsonProperty("middle_name") @ExcludeMissing private val middleName: JsonField, @JsonProperty("phone_numbers") @ExcludeMissing - private val phoneNumbers: JsonField> = JsonMissing.of(), + private val phoneNumbers: JsonField>, @JsonProperty("preferred_name") @ExcludeMissing - private val preferredName: JsonField = JsonMissing.of(), - @JsonProperty("residence") - @ExcludeMissing - private val residence: JsonField = JsonMissing.of(), - @JsonProperty("source_id") - @ExcludeMissing - private val sourceId: JsonField = JsonMissing.of(), - @JsonProperty("ssn") @ExcludeMissing private val ssn: JsonField = JsonMissing.of(), - @JsonProperty("start_date") - @ExcludeMissing - private val startDate: JsonField = JsonMissing.of(), - @JsonProperty("title") - @ExcludeMissing - private val title: JsonField = JsonMissing.of(), + private val preferredName: JsonField, + @JsonProperty("residence") @ExcludeMissing private val residence: JsonField, + @JsonProperty("source_id") @ExcludeMissing private val sourceId: JsonField, + @JsonProperty("ssn") @ExcludeMissing private val ssn: JsonField, + @JsonProperty("start_date") @ExcludeMissing private val startDate: JsonField, + @JsonProperty("title") @ExcludeMissing private val title: JsonField, ) { - /** Worker's compensation classification code for this employee */ - fun classCode(): Optional = Optional.ofNullable(classCode.getNullable("class_code")) + /** + * Worker's compensation classification code for this employee + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun classCode(): Optional = classCode.getOptional("class_code") /** * Custom fields for the individual. These are fields which are defined by the employer in * the system. Custom fields are not currently supported for assisted connections. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun customFields(): Optional> = - Optional.ofNullable(customFields.getNullable("custom_fields")) + fun customFields(): Optional> = customFields.getOptional("custom_fields") - /** The department object. */ - fun department(): Optional = - Optional.ofNullable(department.getNullable("department")) + /** + * The department object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun department(): Optional = department.getOptional("department") - fun dob(): Optional = Optional.ofNullable(dob.getNullable("dob")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun dob(): Optional = dob.getOptional("dob") - fun emails(): Optional> = Optional.ofNullable(emails.getNullable("emails")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun emails(): Optional> = emails.getOptional("emails") - /** The employment object. */ - fun employment(): Optional = - Optional.ofNullable(employment.getNullable("employment")) + /** + * The employment object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun employment(): Optional = employment.getOptional("employment") - /** The detailed employment status of the individual. */ + /** + * The detailed employment status of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun employmentStatus(): Optional = - Optional.ofNullable(employmentStatus.getNullable("employment_status")) + employmentStatus.getOptional("employment_status") /** * Social Security Number of the individual in **encrypted** format. This field is only * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set * in the body. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun encryptedSsn(): Optional = - Optional.ofNullable(encryptedSsn.getNullable("encrypted_ssn")) + fun encryptedSsn(): Optional = encryptedSsn.getOptional("encrypted_ssn") - fun endDate(): Optional = Optional.ofNullable(endDate.getNullable("end_date")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun endDate(): Optional = endDate.getOptional("end_date") - /** The EEOC-defined ethnicity of the individual. */ - fun ethnicity(): Optional = - Optional.ofNullable(ethnicity.getNullable("ethnicity")) + /** + * The EEOC-defined ethnicity of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun ethnicity(): Optional = ethnicity.getOptional("ethnicity") - /** The legal first name of the individual. */ - fun firstName(): Optional = Optional.ofNullable(firstName.getNullable("first_name")) + /** + * The legal first name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") - /** The gender of the individual. */ - fun gender(): Optional = Optional.ofNullable(gender.getNullable("gender")) + /** + * The gender of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun gender(): Optional = gender.getOptional("gender") /** * The employee's income as reported by the provider. This may not always be annualized * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what * information the provider returns. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun income(): Optional = Optional.ofNullable(income.getNullable("income")) + fun income(): Optional = income.getOptional("income") - /** The array of income history. */ - fun incomeHistory(): Optional> = - Optional.ofNullable(incomeHistory.getNullable("income_history")) + /** + * The array of income history. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun incomeHistory(): Optional> = incomeHistory.getOptional("income_history") - /** `true` if the individual an an active employee or contractor at the company. */ - fun isActive(): Optional = Optional.ofNullable(isActive.getNullable("is_active")) + /** + * `true` if the individual an an active employee or contractor at the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isActive(): Optional = isActive.getOptional("is_active") - /** The legal last name of the individual. */ - fun lastName(): Optional = Optional.ofNullable(lastName.getNullable("last_name")) + /** + * The legal last name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun latestRehireDate(): Optional = - Optional.ofNullable(latestRehireDate.getNullable("latest_rehire_date")) + latestRehireDate.getOptional("latest_rehire_date") - fun location(): Optional = Optional.ofNullable(location.getNullable("location")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun location(): Optional = location.getOptional("location") - /** The manager object representing the manager of the individual within the org. */ - fun manager(): Optional = Optional.ofNullable(manager.getNullable("manager")) + /** + * The manager object representing the manager of the individual within the org. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun manager(): Optional = manager.getOptional("manager") - /** The legal middle name of the individual. */ - fun middleName(): Optional = - Optional.ofNullable(middleName.getNullable("middle_name")) + /** + * The legal middle name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") - fun phoneNumbers(): Optional> = - Optional.ofNullable(phoneNumbers.getNullable("phone_numbers")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun phoneNumbers(): Optional> = phoneNumbers.getOptional("phone_numbers") - /** The preferred name of the individual. */ - fun preferredName(): Optional = - Optional.ofNullable(preferredName.getNullable("preferred_name")) + /** + * The preferred name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun preferredName(): Optional = preferredName.getOptional("preferred_name") - fun residence(): Optional = - Optional.ofNullable(residence.getNullable("residence")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun residence(): Optional = residence.getOptional("residence") - /** The source system's unique employment identifier for this individual */ - fun sourceId(): Optional = Optional.ofNullable(sourceId.getNullable("source_id")) + /** + * The source system's unique employment identifier for this individual + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun sourceId(): Optional = sourceId.getOptional("source_id") /** * Social Security Number of the individual. This field is only available with the `ssn` * scope enabled and the `options: { include: ['ssn'] }` param set in the body. * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun ssn(): Optional = Optional.ofNullable(ssn.getNullable("ssn")) + fun ssn(): Optional = ssn.getOptional("ssn") - fun startDate(): Optional = Optional.ofNullable(startDate.getNullable("start_date")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun startDate(): Optional = startDate.getOptional("start_date") - /** The current title of the individual. */ - fun title(): Optional = Optional.ofNullable(title.getNullable("title")) + /** + * The current title of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun title(): Optional = title.getOptional("title") - /** Worker's compensation classification code for this employee */ + /** + * Returns the raw JSON value of [classCode]. + * + * Unlike [classCode], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("class_code") @ExcludeMissing fun _classCode(): JsonField = classCode /** - * Custom fields for the individual. These are fields which are defined by the employer in - * the system. Custom fields are not currently supported for assisted connections. + * Returns the raw JSON value of [customFields]. + * + * Unlike [customFields], this method doesn't throw if the JSON field has an unexpected + * type. */ @JsonProperty("custom_fields") @ExcludeMissing fun _customFields(): JsonField> = customFields - /** The department object. */ + /** + * Returns the raw JSON value of [department]. + * + * Unlike [department], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("department") @ExcludeMissing fun _department(): JsonField = department + /** + * Returns the raw JSON value of [dob]. + * + * Unlike [dob], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("dob") @ExcludeMissing fun _dob(): JsonField = dob + /** + * Returns the raw JSON value of [emails]. + * + * Unlike [emails], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("emails") @ExcludeMissing fun _emails(): JsonField> = emails - /** The employment object. */ + /** + * Returns the raw JSON value of [employment]. + * + * Unlike [employment], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("employment") @ExcludeMissing fun _employment(): JsonField = employment - /** The detailed employment status of the individual. */ + /** + * Returns the raw JSON value of [employmentStatus]. + * + * Unlike [employmentStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("employment_status") @ExcludeMissing fun _employmentStatus(): JsonField = employmentStatus /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set - * in the body. + * Returns the raw JSON value of [encryptedSsn]. + * + * Unlike [encryptedSsn], this method doesn't throw if the JSON field has an unexpected + * type. */ @JsonProperty("encrypted_ssn") @ExcludeMissing fun _encryptedSsn(): JsonField = encryptedSsn + /** + * Returns the raw JSON value of [endDate]. + * + * Unlike [endDate], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("end_date") @ExcludeMissing fun _endDate(): JsonField = endDate - /** The EEOC-defined ethnicity of the individual. */ + /** + * Returns the raw JSON value of [ethnicity]. + * + * Unlike [ethnicity], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("ethnicity") @ExcludeMissing fun _ethnicity(): JsonField = ethnicity - /** The legal first name of the individual. */ + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName - /** The gender of the individual. */ + /** + * Returns the raw JSON value of [gender]. + * + * Unlike [gender], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("gender") @ExcludeMissing fun _gender(): JsonField = gender /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. + * Returns the raw JSON value of [income]. + * + * Unlike [income], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("income") @ExcludeMissing fun _income(): JsonField = income - /** The array of income history. */ + /** + * Returns the raw JSON value of [incomeHistory]. + * + * Unlike [incomeHistory], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("income_history") @ExcludeMissing fun _incomeHistory(): JsonField> = incomeHistory - /** `true` if the individual an an active employee or contractor at the company. */ + /** + * Returns the raw JSON value of [isActive]. + * + * Unlike [isActive], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("is_active") @ExcludeMissing fun _isActive(): JsonField = isActive - /** The legal last name of the individual. */ + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName + /** + * Returns the raw JSON value of [latestRehireDate]. + * + * Unlike [latestRehireDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("latest_rehire_date") @ExcludeMissing fun _latestRehireDate(): JsonField = latestRehireDate + /** + * Returns the raw JSON value of [location]. + * + * Unlike [location], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("location") @ExcludeMissing fun _location(): JsonField = location - /** The manager object representing the manager of the individual within the org. */ + /** + * Returns the raw JSON value of [manager]. + * + * Unlike [manager], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("manager") @ExcludeMissing fun _manager(): JsonField = manager - /** The legal middle name of the individual. */ + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("middle_name") @ExcludeMissing fun _middleName(): JsonField = middleName + /** + * Returns the raw JSON value of [phoneNumbers]. + * + * Unlike [phoneNumbers], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("phone_numbers") @ExcludeMissing fun _phoneNumbers(): JsonField> = phoneNumbers - /** The preferred name of the individual. */ + /** + * Returns the raw JSON value of [preferredName]. + * + * Unlike [preferredName], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("preferred_name") @ExcludeMissing fun _preferredName(): JsonField = preferredName - @JsonProperty("residence") @ExcludeMissing fun _residence(): JsonField = residence - - /** The source system's unique employment identifier for this individual */ - @JsonProperty("source_id") @ExcludeMissing fun _sourceId(): JsonField = sourceId - /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). - */ - @JsonProperty("ssn") @ExcludeMissing fun _ssn(): JsonField = ssn - - @JsonProperty("start_date") @ExcludeMissing fun _startDate(): JsonField = startDate - - /** The current title of the individual. */ - @JsonProperty("title") @ExcludeMissing fun _title(): JsonField = title - - private var validated: Boolean = false - - fun validate(): IndividualOrEmployment = apply { - if (validated) { - return@apply - } - - classCode() - customFields().ifPresent { it.forEach { it.validate() } } - department().ifPresent { it.validate() } - dob() - emails().ifPresent { it.forEach { it.validate() } } - employment().ifPresent { it.validate() } - employmentStatus() - encryptedSsn() - endDate() - ethnicity() - firstName() - gender() - income().ifPresent { it.validate() } - incomeHistory().ifPresent { it.forEach { it?.validate() } } - isActive() - lastName() - latestRehireDate() - location().ifPresent { it.validate() } - manager().ifPresent { it.validate() } - middleName() - phoneNumbers().ifPresent { it.forEach { it?.validate() } } - preferredName() - residence().ifPresent { it.validate() } - sourceId() - ssn() - startDate() - title() - validated = true - } + * Returns the raw JSON value of [residence]. + * + * Unlike [residence], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("residence") @ExcludeMissing fun _residence(): JsonField = residence + + /** + * Returns the raw JSON value of [sourceId]. + * + * Unlike [sourceId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("source_id") @ExcludeMissing fun _sourceId(): JsonField = sourceId + + /** + * Returns the raw JSON value of [ssn]. + * + * Unlike [ssn], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("ssn") @ExcludeMissing fun _ssn(): JsonField = ssn + + /** + * Returns the raw JSON value of [startDate]. + * + * Unlike [startDate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("start_date") @ExcludeMissing fun _startDate(): JsonField = startDate + + /** + * Returns the raw JSON value of [title]. + * + * Unlike [title], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("title") @ExcludeMissing fun _title(): JsonField = title fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [IndividualOrEmployment]. + */ @JvmStatic fun builder() = Builder() } @@ -448,10 +747,16 @@ private constructor( /** Worker's compensation classification code for this employee */ fun classCode(classCode: String?) = classCode(JsonField.ofNullable(classCode)) - /** Worker's compensation classification code for this employee */ - fun classCode(classCode: Optional) = classCode(classCode.orElse(null)) + /** Alias for calling [Builder.classCode] with `classCode.orElse(null)`. */ + fun classCode(classCode: Optional) = classCode(classCode.getOrNull()) - /** Worker's compensation classification code for this employee */ + /** + * Sets [Builder.classCode] to an arbitrary JSON value. + * + * You should usually call [Builder.classCode] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun classCode(classCode: JsonField) = apply { this.classCode = classCode } /** @@ -462,75 +767,100 @@ private constructor( customFields(JsonField.of(customFields)) /** - * Custom fields for the individual. These are fields which are defined by the employer - * in the system. Custom fields are not currently supported for assisted connections. + * Sets [Builder.customFields] to an arbitrary JSON value. + * + * You should usually call [Builder.customFields] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. */ fun customFields(customFields: JsonField>) = apply { this.customFields = customFields.map { it.toMutableList() } } /** - * Custom fields for the individual. These are fields which are defined by the employer - * in the system. Custom fields are not currently supported for assisted connections. + * Adds a single [CustomField] to [customFields]. + * + * @throws IllegalStateException if the field was previously set to a non-list. */ fun addCustomField(customField: CustomField) = apply { customFields = - (customFields ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(customField) + (customFields ?: JsonField.of(mutableListOf())).also { + checkKnown("customFields", it).add(customField) } } /** The department object. */ fun department(department: Department?) = department(JsonField.ofNullable(department)) - /** The department object. */ - fun department(department: Optional) = department(department.orElse(null)) + /** Alias for calling [Builder.department] with `department.orElse(null)`. */ + fun department(department: Optional) = department(department.getOrNull()) - /** The department object. */ + /** + * Sets [Builder.department] to an arbitrary JSON value. + * + * You should usually call [Builder.department] with a well-typed [Department] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun department(department: JsonField) = apply { this.department = department } fun dob(dob: String?) = dob(JsonField.ofNullable(dob)) - fun dob(dob: Optional) = dob(dob.orElse(null)) + /** Alias for calling [Builder.dob] with `dob.orElse(null)`. */ + fun dob(dob: Optional) = dob(dob.getOrNull()) + /** + * Sets [Builder.dob] to an arbitrary JSON value. + * + * You should usually call [Builder.dob] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun dob(dob: JsonField) = apply { this.dob = dob } fun emails(emails: List?) = emails(JsonField.ofNullable(emails)) - fun emails(emails: Optional>) = emails(emails.orElse(null)) + /** Alias for calling [Builder.emails] with `emails.orElse(null)`. */ + fun emails(emails: Optional>) = emails(emails.getOrNull()) + /** + * Sets [Builder.emails] to an arbitrary JSON value. + * + * You should usually call [Builder.emails] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun emails(emails: JsonField>) = apply { this.emails = emails.map { it.toMutableList() } } + /** + * Adds a single [Email] to [emails]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addEmail(email: Email) = apply { emails = - (emails ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(email) + (emails ?: JsonField.of(mutableListOf())).also { + checkKnown("emails", it).add(email) } } /** The employment object. */ fun employment(employment: Employment?) = employment(JsonField.ofNullable(employment)) - /** The employment object. */ - fun employment(employment: Optional) = employment(employment.orElse(null)) + /** Alias for calling [Builder.employment] with `employment.orElse(null)`. */ + fun employment(employment: Optional) = employment(employment.getOrNull()) - /** The employment object. */ + /** + * Sets [Builder.employment] to an arbitrary JSON value. + * + * You should usually call [Builder.employment] with a well-typed [Employment] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun employment(employment: JsonField) = apply { this.employment = employment } @@ -539,11 +869,19 @@ private constructor( fun employmentStatus(employmentStatus: EmploymentStatus?) = employmentStatus(JsonField.ofNullable(employmentStatus)) - /** The detailed employment status of the individual. */ + /** + * Alias for calling [Builder.employmentStatus] with `employmentStatus.orElse(null)`. + */ fun employmentStatus(employmentStatus: Optional) = - employmentStatus(employmentStatus.orElse(null)) + employmentStatus(employmentStatus.getOrNull()) - /** The detailed employment status of the individual. */ + /** + * Sets [Builder.employmentStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.employmentStatus] with a well-typed + * [EmploymentStatus] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ fun employmentStatus(employmentStatus: JsonField) = apply { this.employmentStatus = employmentStatus } @@ -556,18 +894,16 @@ private constructor( fun encryptedSsn(encryptedSsn: String?) = encryptedSsn(JsonField.ofNullable(encryptedSsn)) - /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param - * set in the body. - */ + /** Alias for calling [Builder.encryptedSsn] with `encryptedSsn.orElse(null)`. */ fun encryptedSsn(encryptedSsn: Optional) = - encryptedSsn(encryptedSsn.orElse(null)) + encryptedSsn(encryptedSsn.getOrNull()) /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param - * set in the body. + * Sets [Builder.encryptedSsn] to an arbitrary JSON value. + * + * You should usually call [Builder.encryptedSsn] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun encryptedSsn(encryptedSsn: JsonField) = apply { this.encryptedSsn = encryptedSsn @@ -575,35 +911,61 @@ private constructor( fun endDate(endDate: String?) = endDate(JsonField.ofNullable(endDate)) - fun endDate(endDate: Optional) = endDate(endDate.orElse(null)) + /** Alias for calling [Builder.endDate] with `endDate.orElse(null)`. */ + fun endDate(endDate: Optional) = endDate(endDate.getOrNull()) + /** + * Sets [Builder.endDate] to an arbitrary JSON value. + * + * You should usually call [Builder.endDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun endDate(endDate: JsonField) = apply { this.endDate = endDate } /** The EEOC-defined ethnicity of the individual. */ fun ethnicity(ethnicity: Ethnicity?) = ethnicity(JsonField.ofNullable(ethnicity)) - /** The EEOC-defined ethnicity of the individual. */ - fun ethnicity(ethnicity: Optional) = ethnicity(ethnicity.orElse(null)) + /** Alias for calling [Builder.ethnicity] with `ethnicity.orElse(null)`. */ + fun ethnicity(ethnicity: Optional) = ethnicity(ethnicity.getOrNull()) - /** The EEOC-defined ethnicity of the individual. */ + /** + * Sets [Builder.ethnicity] to an arbitrary JSON value. + * + * You should usually call [Builder.ethnicity] with a well-typed [Ethnicity] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun ethnicity(ethnicity: JsonField) = apply { this.ethnicity = ethnicity } /** The legal first name of the individual. */ fun firstName(firstName: String?) = firstName(JsonField.ofNullable(firstName)) - /** The legal first name of the individual. */ - fun firstName(firstName: Optional) = firstName(firstName.orElse(null)) + /** Alias for calling [Builder.firstName] with `firstName.orElse(null)`. */ + fun firstName(firstName: Optional) = firstName(firstName.getOrNull()) - /** The legal first name of the individual. */ + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun firstName(firstName: JsonField) = apply { this.firstName = firstName } /** The gender of the individual. */ fun gender(gender: Gender?) = gender(JsonField.ofNullable(gender)) - /** The gender of the individual. */ - fun gender(gender: Optional) = gender(gender.orElse(null)) + /** Alias for calling [Builder.gender] with `gender.orElse(null)`. */ + fun gender(gender: Optional) = gender(gender.getOrNull()) - /** The gender of the individual. */ + /** + * Sets [Builder.gender] to an arbitrary JSON value. + * + * You should usually call [Builder.gender] with a well-typed [Gender] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun gender(gender: JsonField) = apply { this.gender = gender } /** @@ -613,17 +975,15 @@ private constructor( */ fun income(income: Income?) = income(JsonField.ofNullable(income)) - /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. - */ - fun income(income: Optional) = income(income.orElse(null)) + /** Alias for calling [Builder.income] with `income.orElse(null)`. */ + fun income(income: Optional) = income(income.getOrNull()) /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. + * Sets [Builder.income] to an arbitrary JSON value. + * + * You should usually call [Builder.income] with a well-typed [Income] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun income(income: JsonField) = apply { this.income = income } @@ -631,105 +991,161 @@ private constructor( fun incomeHistory(incomeHistory: List?) = incomeHistory(JsonField.ofNullable(incomeHistory)) - /** The array of income history. */ + /** Alias for calling [Builder.incomeHistory] with `incomeHistory.orElse(null)`. */ fun incomeHistory(incomeHistory: Optional>) = - incomeHistory(incomeHistory.orElse(null)) + incomeHistory(incomeHistory.getOrNull()) - /** The array of income history. */ + /** + * Sets [Builder.incomeHistory] to an arbitrary JSON value. + * + * You should usually call [Builder.incomeHistory] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun incomeHistory(incomeHistory: JsonField>) = apply { this.incomeHistory = incomeHistory.map { it.toMutableList() } } - /** The array of income history. */ + /** + * Adds a single [Income] to [Builder.incomeHistory]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addIncomeHistory(incomeHistory: Income) = apply { this.incomeHistory = - (this.incomeHistory ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(incomeHistory) + (this.incomeHistory ?: JsonField.of(mutableListOf())).also { + checkKnown("incomeHistory", it).add(incomeHistory) } } /** `true` if the individual an an active employee or contractor at the company. */ fun isActive(isActive: Boolean?) = isActive(JsonField.ofNullable(isActive)) - /** `true` if the individual an an active employee or contractor at the company. */ + /** + * Alias for [Builder.isActive]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun isActive(isActive: Boolean) = isActive(isActive as Boolean?) - /** `true` if the individual an an active employee or contractor at the company. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun isActive(isActive: Optional) = isActive(isActive.orElse(null) as Boolean?) + /** Alias for calling [Builder.isActive] with `isActive.orElse(null)`. */ + fun isActive(isActive: Optional) = isActive(isActive.getOrNull()) - /** `true` if the individual an an active employee or contractor at the company. */ + /** + * Sets [Builder.isActive] to an arbitrary JSON value. + * + * You should usually call [Builder.isActive] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun isActive(isActive: JsonField) = apply { this.isActive = isActive } /** The legal last name of the individual. */ fun lastName(lastName: String?) = lastName(JsonField.ofNullable(lastName)) - /** The legal last name of the individual. */ - fun lastName(lastName: Optional) = lastName(lastName.orElse(null)) + /** Alias for calling [Builder.lastName] with `lastName.orElse(null)`. */ + fun lastName(lastName: Optional) = lastName(lastName.getOrNull()) - /** The legal last name of the individual. */ + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun lastName(lastName: JsonField) = apply { this.lastName = lastName } fun latestRehireDate(latestRehireDate: String?) = latestRehireDate(JsonField.ofNullable(latestRehireDate)) + /** + * Alias for calling [Builder.latestRehireDate] with `latestRehireDate.orElse(null)`. + */ fun latestRehireDate(latestRehireDate: Optional) = - latestRehireDate(latestRehireDate.orElse(null)) + latestRehireDate(latestRehireDate.getOrNull()) + /** + * Sets [Builder.latestRehireDate] to an arbitrary JSON value. + * + * You should usually call [Builder.latestRehireDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun latestRehireDate(latestRehireDate: JsonField) = apply { this.latestRehireDate = latestRehireDate } fun location(location: Location?) = location(JsonField.ofNullable(location)) - fun location(location: Optional) = location(location.orElse(null)) + /** Alias for calling [Builder.location] with `location.orElse(null)`. */ + fun location(location: Optional) = location(location.getOrNull()) + /** + * Sets [Builder.location] to an arbitrary JSON value. + * + * You should usually call [Builder.location] with a well-typed [Location] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun location(location: JsonField) = apply { this.location = location } /** The manager object representing the manager of the individual within the org. */ fun manager(manager: Manager?) = manager(JsonField.ofNullable(manager)) - /** The manager object representing the manager of the individual within the org. */ - fun manager(manager: Optional) = manager(manager.orElse(null)) + /** Alias for calling [Builder.manager] with `manager.orElse(null)`. */ + fun manager(manager: Optional) = manager(manager.getOrNull()) - /** The manager object representing the manager of the individual within the org. */ + /** + * Sets [Builder.manager] to an arbitrary JSON value. + * + * You should usually call [Builder.manager] with a well-typed [Manager] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun manager(manager: JsonField) = apply { this.manager = manager } /** The legal middle name of the individual. */ fun middleName(middleName: String?) = middleName(JsonField.ofNullable(middleName)) - /** The legal middle name of the individual. */ - fun middleName(middleName: Optional) = middleName(middleName.orElse(null)) + /** Alias for calling [Builder.middleName] with `middleName.orElse(null)`. */ + fun middleName(middleName: Optional) = middleName(middleName.getOrNull()) - /** The legal middle name of the individual. */ + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun middleName(middleName: JsonField) = apply { this.middleName = middleName } fun phoneNumbers(phoneNumbers: List?) = phoneNumbers(JsonField.ofNullable(phoneNumbers)) + /** Alias for calling [Builder.phoneNumbers] with `phoneNumbers.orElse(null)`. */ fun phoneNumbers(phoneNumbers: Optional>) = - phoneNumbers(phoneNumbers.orElse(null)) + phoneNumbers(phoneNumbers.getOrNull()) + /** + * Sets [Builder.phoneNumbers] to an arbitrary JSON value. + * + * You should usually call [Builder.phoneNumbers] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun phoneNumbers(phoneNumbers: JsonField>) = apply { this.phoneNumbers = phoneNumbers.map { it.toMutableList() } } + /** + * Adds a single [PhoneNumber] to [phoneNumbers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addPhoneNumber(phoneNumber: PhoneNumber) = apply { phoneNumbers = - (phoneNumbers ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(phoneNumber) + (phoneNumbers ?: JsonField.of(mutableListOf())).also { + checkKnown("phoneNumbers", it).add(phoneNumber) } } @@ -737,25 +1153,45 @@ private constructor( fun preferredName(preferredName: String?) = preferredName(JsonField.ofNullable(preferredName)) - /** The preferred name of the individual. */ + /** Alias for calling [Builder.preferredName] with `preferredName.orElse(null)`. */ fun preferredName(preferredName: Optional) = - preferredName(preferredName.orElse(null)) + preferredName(preferredName.getOrNull()) - /** The preferred name of the individual. */ + /** + * Sets [Builder.preferredName] to an arbitrary JSON value. + * + * You should usually call [Builder.preferredName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun preferredName(preferredName: JsonField) = apply { this.preferredName = preferredName } fun residence(residence: Location?) = residence(JsonField.ofNullable(residence)) - fun residence(residence: Optional) = residence(residence.orElse(null)) + /** Alias for calling [Builder.residence] with `residence.orElse(null)`. */ + fun residence(residence: Optional) = residence(residence.getOrNull()) + /** + * Sets [Builder.residence] to an arbitrary JSON value. + * + * You should usually call [Builder.residence] with a well-typed [Location] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun residence(residence: JsonField) = apply { this.residence = residence } /** The source system's unique employment identifier for this individual */ fun sourceId(sourceId: String) = sourceId(JsonField.of(sourceId)) - /** The source system's unique employment identifier for this individual */ + /** + * Sets [Builder.sourceId] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun sourceId(sourceId: JsonField) = apply { this.sourceId = sourceId } /** @@ -765,35 +1201,52 @@ private constructor( */ fun ssn(ssn: String?) = ssn(JsonField.ofNullable(ssn)) - /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). - */ - fun ssn(ssn: Optional) = ssn(ssn.orElse(null)) + /** Alias for calling [Builder.ssn] with `ssn.orElse(null)`. */ + fun ssn(ssn: Optional) = ssn(ssn.getOrNull()) /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). + * Sets [Builder.ssn] to an arbitrary JSON value. + * + * You should usually call [Builder.ssn] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. */ fun ssn(ssn: JsonField) = apply { this.ssn = ssn } fun startDate(startDate: String?) = startDate(JsonField.ofNullable(startDate)) - fun startDate(startDate: Optional) = startDate(startDate.orElse(null)) + /** Alias for calling [Builder.startDate] with `startDate.orElse(null)`. */ + fun startDate(startDate: Optional) = startDate(startDate.getOrNull()) + /** + * Sets [Builder.startDate] to an arbitrary JSON value. + * + * You should usually call [Builder.startDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun startDate(startDate: JsonField) = apply { this.startDate = startDate } /** The current title of the individual. */ fun title(title: String?) = title(JsonField.ofNullable(title)) - /** The current title of the individual. */ - fun title(title: Optional) = title(title.orElse(null)) + /** Alias for calling [Builder.title] with `title.orElse(null)`. */ + fun title(title: Optional) = title(title.getOrNull()) - /** The current title of the individual. */ + /** + * Sets [Builder.title] to an arbitrary JSON value. + * + * You should usually call [Builder.title] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun title(title: JsonField) = apply { this.title = title } + /** + * Returns an immutable instance of [IndividualOrEmployment]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): IndividualOrEmployment = IndividualOrEmployment( classCode, @@ -826,43 +1279,131 @@ private constructor( ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): IndividualOrEmployment = apply { + if (validated) { + return@apply + } + + classCode() + customFields().ifPresent { it.forEach { it.validate() } } + department().ifPresent { it.validate() } + dob() + emails().ifPresent { it.forEach { it.validate() } } + employment().ifPresent { it.validate() } + employmentStatus().ifPresent { it.validate() } + encryptedSsn() + endDate() + ethnicity().ifPresent { it.validate() } + firstName() + gender().ifPresent { it.validate() } + income().ifPresent { it.validate() } + incomeHistory().ifPresent { it.forEach { it?.validate() } } + isActive() + lastName() + latestRehireDate() + location().ifPresent { it.validate() } + manager().ifPresent { it.validate() } + middleName() + phoneNumbers().ifPresent { it.forEach { it?.validate() } } + preferredName() + residence().ifPresent { it.validate() } + sourceId() + ssn() + startDate() + title() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (classCode.asKnown().isPresent) 1 else 0) + + (customFields.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (department.asKnown().getOrNull()?.validity() ?: 0) + + (if (dob.asKnown().isPresent) 1 else 0) + + (emails.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (employment.asKnown().getOrNull()?.validity() ?: 0) + + (employmentStatus.asKnown().getOrNull()?.validity() ?: 0) + + (if (encryptedSsn.asKnown().isPresent) 1 else 0) + + (if (endDate.asKnown().isPresent) 1 else 0) + + (ethnicity.asKnown().getOrNull()?.validity() ?: 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (gender.asKnown().getOrNull()?.validity() ?: 0) + + (income.asKnown().getOrNull()?.validity() ?: 0) + + (incomeHistory.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } + ?: 0) + + (if (isActive.asKnown().isPresent) 1 else 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (if (latestRehireDate.asKnown().isPresent) 1 else 0) + + (location.asKnown().getOrNull()?.validity() ?: 0) + + (manager.asKnown().getOrNull()?.validity() ?: 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + + (phoneNumbers.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (preferredName.asKnown().isPresent) 1 else 0) + + (residence.asKnown().getOrNull()?.validity() ?: 0) + + (if (sourceId.asKnown().isPresent) 1 else 0) + + (if (ssn.asKnown().isPresent) 1 else 0) + + (if (startDate.asKnown().isPresent) 1 else 0) + + (if (title.asKnown().isPresent) 1 else 0) + class CustomField - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("value") @ExcludeMissing private val value: JsonValue = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val value: JsonValue, + private val additionalProperties: MutableMap, ) { - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonValue = JsonMissing.of(), + ) : this(name, value, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") @JsonProperty("value") @ExcludeMissing fun _value(): JsonValue = value + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): CustomField = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [CustomField]. */ @JvmStatic fun builder() = Builder() } @@ -882,8 +1423,16 @@ private constructor( fun name(name: String?) = name(JsonField.ofNullable(name)) - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun value(value: JsonValue) = apply { this.value = value } @@ -910,10 +1459,42 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [CustomField]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): CustomField = - CustomField(name, value, additionalProperties.toImmutable()) + CustomField(name, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CustomField = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -933,42 +1514,47 @@ private constructor( } /** The department object. */ - @NoAutoDetect class Department - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - /** The name of the department associated with the individual. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) + + /** + * The name of the department associated with the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** The name of the department associated with the individual. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Department = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Department]. */ @JvmStatic fun builder() = Builder() } @@ -987,10 +1573,16 @@ private constructor( /** The name of the department associated with the individual. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The name of the department associated with the individual. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The name of the department associated with the individual. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = apply { @@ -1015,9 +1607,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Department = Department(name, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Department]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Department = Department(name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Department = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1036,48 +1660,60 @@ private constructor( "Department{name=$name, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Email - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Email = apply { - if (validated) { - return@apply - } - - data() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Email]. */ @JvmStatic fun builder() = Builder() } @@ -1097,12 +1733,27 @@ private constructor( fun data(data: String) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun type(type: Type?) = type(JsonField.ofNullable(type)) - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -1127,9 +1778,45 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Email = Email(data, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Email]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Email = Email(data, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Email = apply { + if (validated) { + return@apply + } + + data() + type().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -1220,6 +1907,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1252,58 +1966,67 @@ private constructor( } /** The employment object. */ - @NoAutoDetect class Employment - @JsonCreator private constructor( - @JsonProperty("subtype") - @ExcludeMissing - private val subtype: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val subtype: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("subtype") + @ExcludeMissing + subtype: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(subtype, type, mutableMapOf()) + /** * The secondary employment type of the individual. Options: `full_time`, `part_time`, * `intern`, `temp`, `seasonal` and `individual_contractor`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun subtype(): Optional = Optional.ofNullable(subtype.getNullable("subtype")) + fun subtype(): Optional = subtype.getOptional("subtype") - /** The main employment type of the individual. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The main employment type of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") /** - * The secondary employment type of the individual. Options: `full_time`, `part_time`, - * `intern`, `temp`, `seasonal` and `individual_contractor`. + * Returns the raw JSON value of [subtype]. + * + * Unlike [subtype], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype - /** The main employment type of the individual. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Employment = apply { - if (validated) { - return@apply - } - - subtype() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Employment]. */ @JvmStatic fun builder() = Builder() } @@ -1327,25 +2050,31 @@ private constructor( */ fun subtype(subtype: Subtype?) = subtype(JsonField.ofNullable(subtype)) - /** - * The secondary employment type of the individual. Options: `full_time`, - * `part_time`, `intern`, `temp`, `seasonal` and `individual_contractor`. - */ - fun subtype(subtype: Optional) = subtype(subtype.orElse(null)) + /** Alias for calling [Builder.subtype] with `subtype.orElse(null)`. */ + fun subtype(subtype: Optional) = subtype(subtype.getOrNull()) /** - * The secondary employment type of the individual. Options: `full_time`, - * `part_time`, `intern`, `temp`, `seasonal` and `individual_contractor`. + * Sets [Builder.subtype] to an arbitrary JSON value. + * + * You should usually call [Builder.subtype] with a well-typed [Subtype] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. */ fun subtype(subtype: JsonField) = apply { this.subtype = subtype } /** The main employment type of the individual. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** The main employment type of the individual. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** The main employment type of the individual. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -1370,10 +2099,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Employment]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Employment = - Employment(subtype, type, additionalProperties.toImmutable()) + Employment(subtype, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Employment = apply { + if (validated) { + return@apply + } + + subtype().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (subtype.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + /** * The secondary employment type of the individual. Options: `full_time`, `part_time`, * `intern`, `temp`, `seasonal` and `individual_contractor`. @@ -1493,6 +2258,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Subtype = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1597,6 +2389,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1752,6 +2571,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EmploymentStatus = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1895,6 +2741,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Ethnicity = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2010,6 +2883,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Gender = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2024,42 +2924,47 @@ private constructor( } /** The manager object representing the manager of the individual within the org. */ - @NoAutoDetect class Manager - @JsonCreator private constructor( - @JsonProperty("id") - @ExcludeMissing - private val id: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val additionalProperties: MutableMap, ) { - /** A stable Finch `id` (UUID v4) for an individual in the company. */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of() + ) : this(id, mutableMapOf()) + + /** + * A stable Finch `id` (UUID v4) for an individual in the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Manager = apply { - if (validated) { - return@apply - } - - id() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Manager]. */ @JvmStatic fun builder() = Builder() } @@ -2078,7 +2983,13 @@ private constructor( /** A stable Finch `id` (UUID v4) for an individual in the company. */ fun id(id: String) = id(JsonField.of(id)) - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun id(id: JsonField) = apply { this.id = id } fun additionalProperties(additionalProperties: Map) = apply { @@ -2103,9 +3014,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Manager = Manager(id, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Manager]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Manager = Manager(id, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Manager = apply { + if (validated) { + return@apply + } + + id() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (id.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2123,48 +3066,60 @@ private constructor( override fun toString() = "Manager{id=$id, additionalProperties=$additionalProperties}" } - @NoAutoDetect class PhoneNumber - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PhoneNumber = apply { - if (validated) { - return@apply - } - - data() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [PhoneNumber]. */ @JvmStatic fun builder() = Builder() } @@ -2182,14 +3137,32 @@ private constructor( additionalProperties = phoneNumber.additionalProperties.toMutableMap() } - fun data(data: String) = data(JsonField.of(data)) + fun data(data: String?) = data(JsonField.ofNullable(data)) + + /** Alias for calling [Builder.data] with `data.orElse(null)`. */ + fun data(data: Optional) = data(data.getOrNull()) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun data(data: JsonField) = apply { this.data = data } fun type(type: Type?) = type(JsonField.ofNullable(type)) - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -2214,10 +3187,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PhoneNumber]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): PhoneNumber = - PhoneNumber(data, type, additionalProperties.toImmutable()) + PhoneNumber(data, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): PhoneNumber = apply { + if (validated) { + return@apply + } + + data() + type().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -2308,6 +3317,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2357,156 +3393,6 @@ private constructor( "IndividualOrEmployment{classCode=$classCode, customFields=$customFields, department=$department, dob=$dob, emails=$emails, employment=$employment, employmentStatus=$employmentStatus, encryptedSsn=$encryptedSsn, endDate=$endDate, ethnicity=$ethnicity, firstName=$firstName, gender=$gender, income=$income, incomeHistory=$incomeHistory, isActive=$isActive, lastName=$lastName, latestRehireDate=$latestRehireDate, location=$location, manager=$manager, middleName=$middleName, phoneNumbers=$phoneNumbers, preferredName=$preferredName, residence=$residence, sourceId=$sourceId, ssn=$ssn, startDate=$startDate, title=$title}" } - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun none(): SandboxDirectoryCreateParams = builder().build() - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [SandboxDirectoryCreateParams]. */ - @NoAutoDetect - class Builder internal constructor() { - - private var body: MutableList? = null - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - - @JvmSynthetic - internal fun from(sandboxDirectoryCreateParams: SandboxDirectoryCreateParams) = apply { - body = sandboxDirectoryCreateParams.body?.toMutableList() - additionalHeaders = sandboxDirectoryCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = sandboxDirectoryCreateParams.additionalQueryParams.toBuilder() - } - - /** - * Array of individuals to create. Takes all combined fields from `/individual` and - * `/employment` endpoints. All fields are optional. - */ - fun body(body: List?) = apply { this.body = body?.toMutableList() } - - /** - * Array of individuals to create. Takes all combined fields from `/individual` and - * `/employment` endpoints. All fields are optional. - */ - fun body(body: Optional>) = body(body.orElse(null)) - - /** - * Array of individuals to create. Takes all combined fields from `/individual` and - * `/employment` endpoints. All fields are optional. - */ - fun addBody(body: IndividualOrEmployment) = apply { - this.body = (this.body ?: mutableListOf()).apply { add(body) } - } - - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } - - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } - - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } - - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } - - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } - - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } - - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } - - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } - - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } - - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } - - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } - - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } - - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } - - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } - - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } - - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } - - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) - } - - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } - - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } - - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) - } - - fun build(): SandboxDirectoryCreateParams = - SandboxDirectoryCreateParams( - body?.toImmutable(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) - } - override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxEmploymentUpdateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxEmploymentUpdateParams.kt index 0eee4350..ef2be056 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxEmploymentUpdateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxEmploymentUpdateParams.kt @@ -11,16 +11,17 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Update sandbox employment */ class SandboxEmploymentUpdateParams @@ -33,118 +34,271 @@ private constructor( fun individualId(): String = individualId - /** Worker's compensation classification code for this employee */ + /** + * Worker's compensation classification code for this employee + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun classCode(): Optional = body.classCode() /** * Custom fields for the individual. These are fields which are defined by the employer in the * system. Custom fields are not currently supported for assisted connections. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ fun customFields(): Optional> = body.customFields() - /** The department object. */ + /** + * The department object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun department(): Optional = body.department() - /** The employment object. */ + /** + * The employment object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun employment(): Optional = body.employment() - /** The detailed employment status of the individual. */ + /** + * The detailed employment status of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun employmentStatus(): Optional = body.employmentStatus() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun endDate(): Optional = body.endDate() - /** The legal first name of the individual. */ + /** + * The legal first name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun firstName(): Optional = body.firstName() /** * The employee's income as reported by the provider. This may not always be annualized income, * but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what information the * provider returns. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ fun income(): Optional = body.income() - /** The array of income history. */ + /** + * The array of income history. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun incomeHistory(): Optional> = body.incomeHistory() - /** `true` if the individual an an active employee or contractor at the company. */ + /** + * `true` if the individual an an active employee or contractor at the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun isActive(): Optional = body.isActive() - /** The legal last name of the individual. */ + /** + * The legal last name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun lastName(): Optional = body.lastName() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun latestRehireDate(): Optional = body.latestRehireDate() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun location(): Optional = body.location() - /** The manager object representing the manager of the individual within the org. */ + /** + * The manager object representing the manager of the individual within the org. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun manager(): Optional = body.manager() - /** The legal middle name of the individual. */ + /** + * The legal middle name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun middleName(): Optional = body.middleName() - /** The source system's unique employment identifier for this individual */ + /** + * The source system's unique employment identifier for this individual + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun sourceId(): Optional = body.sourceId() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun startDate(): Optional = body.startDate() - /** The current title of the individual. */ + /** + * The current title of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun title(): Optional = body.title() - /** Worker's compensation classification code for this employee */ + /** + * Returns the raw JSON value of [classCode]. + * + * Unlike [classCode], this method doesn't throw if the JSON field has an unexpected type. + */ fun _classCode(): JsonField = body._classCode() /** - * Custom fields for the individual. These are fields which are defined by the employer in the - * system. Custom fields are not currently supported for assisted connections. + * Returns the raw JSON value of [customFields]. + * + * Unlike [customFields], this method doesn't throw if the JSON field has an unexpected type. */ fun _customFields(): JsonField> = body._customFields() - /** The department object. */ + /** + * Returns the raw JSON value of [department]. + * + * Unlike [department], this method doesn't throw if the JSON field has an unexpected type. + */ fun _department(): JsonField = body._department() - /** The employment object. */ + /** + * Returns the raw JSON value of [employment]. + * + * Unlike [employment], this method doesn't throw if the JSON field has an unexpected type. + */ fun _employment(): JsonField = body._employment() - /** The detailed employment status of the individual. */ + /** + * Returns the raw JSON value of [employmentStatus]. + * + * Unlike [employmentStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ fun _employmentStatus(): JsonField = body._employmentStatus() + /** + * Returns the raw JSON value of [endDate]. + * + * Unlike [endDate], this method doesn't throw if the JSON field has an unexpected type. + */ fun _endDate(): JsonField = body._endDate() - /** The legal first name of the individual. */ + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an unexpected type. + */ fun _firstName(): JsonField = body._firstName() /** - * The employee's income as reported by the provider. This may not always be annualized income, - * but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what information the - * provider returns. + * Returns the raw JSON value of [income]. + * + * Unlike [income], this method doesn't throw if the JSON field has an unexpected type. */ fun _income(): JsonField = body._income() - /** The array of income history. */ + /** + * Returns the raw JSON value of [incomeHistory]. + * + * Unlike [incomeHistory], this method doesn't throw if the JSON field has an unexpected type. + */ fun _incomeHistory(): JsonField> = body._incomeHistory() - /** `true` if the individual an an active employee or contractor at the company. */ + /** + * Returns the raw JSON value of [isActive]. + * + * Unlike [isActive], this method doesn't throw if the JSON field has an unexpected type. + */ fun _isActive(): JsonField = body._isActive() - /** The legal last name of the individual. */ + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an unexpected type. + */ fun _lastName(): JsonField = body._lastName() + /** + * Returns the raw JSON value of [latestRehireDate]. + * + * Unlike [latestRehireDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ fun _latestRehireDate(): JsonField = body._latestRehireDate() + /** + * Returns the raw JSON value of [location]. + * + * Unlike [location], this method doesn't throw if the JSON field has an unexpected type. + */ fun _location(): JsonField = body._location() - /** The manager object representing the manager of the individual within the org. */ + /** + * Returns the raw JSON value of [manager]. + * + * Unlike [manager], this method doesn't throw if the JSON field has an unexpected type. + */ fun _manager(): JsonField = body._manager() - /** The legal middle name of the individual. */ + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an unexpected type. + */ fun _middleName(): JsonField = body._middleName() - /** The source system's unique employment identifier for this individual */ + /** + * Returns the raw JSON value of [sourceId]. + * + * Unlike [sourceId], this method doesn't throw if the JSON field has an unexpected type. + */ fun _sourceId(): JsonField = body._sourceId() + /** + * Returns the raw JSON value of [startDate]. + * + * Unlike [startDate], this method doesn't throw if the JSON field has an unexpected type. + */ fun _startDate(): JsonField = body._startDate() - /** The current title of the individual. */ + /** + * Returns the raw JSON value of [title]. + * + * Unlike [title], this method doesn't throw if the JSON field has an unexpected type. + */ fun _title(): JsonField = body._title() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -153,961 +307,1441 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): EmploymentWithoutId = body - - override fun _headers(): Headers = additionalHeaders + fun toBuilder() = Builder().from(this) - override fun _queryParams(): QueryParams = additionalQueryParams + companion object { - fun getPathParam(index: Int): String { - return when (index) { - 0 -> individualId - else -> "" - } + /** + * Returns a mutable builder for constructing an instance of + * [SandboxEmploymentUpdateParams]. + * + * The following fields are required: + * ```java + * .individualId() + * ``` + */ + @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class EmploymentWithoutId - @JsonCreator - private constructor( - @JsonProperty("class_code") - @ExcludeMissing - private val classCode: JsonField = JsonMissing.of(), - @JsonProperty("custom_fields") - @ExcludeMissing - private val customFields: JsonField> = JsonMissing.of(), - @JsonProperty("department") - @ExcludeMissing - private val department: JsonField = JsonMissing.of(), - @JsonProperty("employment") - @ExcludeMissing - private val employment: JsonField = JsonMissing.of(), - @JsonProperty("employment_status") - @ExcludeMissing - private val employmentStatus: JsonField = JsonMissing.of(), - @JsonProperty("end_date") - @ExcludeMissing - private val endDate: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("income") - @ExcludeMissing - private val income: JsonField = JsonMissing.of(), - @JsonProperty("income_history") - @ExcludeMissing - private val incomeHistory: JsonField> = JsonMissing.of(), - @JsonProperty("is_active") - @ExcludeMissing - private val isActive: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), - @JsonProperty("latest_rehire_date") - @ExcludeMissing - private val latestRehireDate: JsonField = JsonMissing.of(), - @JsonProperty("location") - @ExcludeMissing - private val location: JsonField = JsonMissing.of(), - @JsonProperty("manager") - @ExcludeMissing - private val manager: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), - @JsonProperty("source_id") - @ExcludeMissing - private val sourceId: JsonField = JsonMissing.of(), - @JsonProperty("start_date") - @ExcludeMissing - private val startDate: JsonField = JsonMissing.of(), - @JsonProperty("title") - @ExcludeMissing - private val title: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + /** A builder for [SandboxEmploymentUpdateParams]. */ + class Builder internal constructor() { - /** Worker's compensation classification code for this employee */ - fun classCode(): Optional = Optional.ofNullable(classCode.getNullable("class_code")) + private var individualId: String? = null + private var body: EmploymentWithoutId.Builder = EmploymentWithoutId.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(sandboxEmploymentUpdateParams: SandboxEmploymentUpdateParams) = apply { + individualId = sandboxEmploymentUpdateParams.individualId + body = sandboxEmploymentUpdateParams.body.toBuilder() + additionalHeaders = sandboxEmploymentUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = sandboxEmploymentUpdateParams.additionalQueryParams.toBuilder() + } + + fun individualId(individualId: String) = apply { this.individualId = individualId } /** - * Custom fields for the individual. These are fields which are defined by the employer in - * the system. Custom fields are not currently supported for assisted connections. + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [classCode] + * - [customFields] + * - [department] + * - [employment] + * - [employmentStatus] + * - etc. */ - fun customFields(): Optional> = - Optional.ofNullable(customFields.getNullable("custom_fields")) + fun body(body: EmploymentWithoutId) = apply { this.body = body.toBuilder() } - /** The department object. */ - fun department(): Optional = - Optional.ofNullable(department.getNullable("department")) + /** Worker's compensation classification code for this employee */ + fun classCode(classCode: String?) = apply { body.classCode(classCode) } - /** The employment object. */ - fun employment(): Optional = - Optional.ofNullable(employment.getNullable("employment")) + /** Alias for calling [Builder.classCode] with `classCode.orElse(null)`. */ + fun classCode(classCode: Optional) = classCode(classCode.getOrNull()) - /** The detailed employment status of the individual. */ - fun employmentStatus(): Optional = - Optional.ofNullable(employmentStatus.getNullable("employment_status")) + /** + * Sets [Builder.classCode] to an arbitrary JSON value. + * + * You should usually call [Builder.classCode] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun classCode(classCode: JsonField) = apply { body.classCode(classCode) } - fun endDate(): Optional = Optional.ofNullable(endDate.getNullable("end_date")) + /** + * Custom fields for the individual. These are fields which are defined by the employer in + * the system. Custom fields are not currently supported for assisted connections. + */ + fun customFields(customFields: List) = apply { + body.customFields(customFields) + } - /** The legal first name of the individual. */ - fun firstName(): Optional = Optional.ofNullable(firstName.getNullable("first_name")) + /** + * Sets [Builder.customFields] to an arbitrary JSON value. + * + * You should usually call [Builder.customFields] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun customFields(customFields: JsonField>) = apply { + body.customFields(customFields) + } /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. + * Adds a single [CustomField] to [customFields]. + * + * @throws IllegalStateException if the field was previously set to a non-list. */ - fun income(): Optional = Optional.ofNullable(income.getNullable("income")) + fun addCustomField(customField: CustomField) = apply { body.addCustomField(customField) } - /** The array of income history. */ - fun incomeHistory(): Optional> = - Optional.ofNullable(incomeHistory.getNullable("income_history")) + /** The department object. */ + fun department(department: Department?) = apply { body.department(department) } - /** `true` if the individual an an active employee or contractor at the company. */ - fun isActive(): Optional = Optional.ofNullable(isActive.getNullable("is_active")) + /** Alias for calling [Builder.department] with `department.orElse(null)`. */ + fun department(department: Optional) = department(department.getOrNull()) - /** The legal last name of the individual. */ - fun lastName(): Optional = Optional.ofNullable(lastName.getNullable("last_name")) + /** + * Sets [Builder.department] to an arbitrary JSON value. + * + * You should usually call [Builder.department] with a well-typed [Department] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun department(department: JsonField) = apply { body.department(department) } - fun latestRehireDate(): Optional = - Optional.ofNullable(latestRehireDate.getNullable("latest_rehire_date")) + /** The employment object. */ + fun employment(employment: Employment?) = apply { body.employment(employment) } - fun location(): Optional = Optional.ofNullable(location.getNullable("location")) + /** Alias for calling [Builder.employment] with `employment.orElse(null)`. */ + fun employment(employment: Optional) = employment(employment.getOrNull()) - /** The manager object representing the manager of the individual within the org. */ - fun manager(): Optional = Optional.ofNullable(manager.getNullable("manager")) + /** + * Sets [Builder.employment] to an arbitrary JSON value. + * + * You should usually call [Builder.employment] with a well-typed [Employment] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun employment(employment: JsonField) = apply { body.employment(employment) } - /** The legal middle name of the individual. */ - fun middleName(): Optional = - Optional.ofNullable(middleName.getNullable("middle_name")) + /** The detailed employment status of the individual. */ + fun employmentStatus(employmentStatus: EmploymentStatus?) = apply { + body.employmentStatus(employmentStatus) + } - /** The source system's unique employment identifier for this individual */ - fun sourceId(): Optional = Optional.ofNullable(sourceId.getNullable("source_id")) + /** Alias for calling [Builder.employmentStatus] with `employmentStatus.orElse(null)`. */ + fun employmentStatus(employmentStatus: Optional) = + employmentStatus(employmentStatus.getOrNull()) - fun startDate(): Optional = Optional.ofNullable(startDate.getNullable("start_date")) + /** + * Sets [Builder.employmentStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.employmentStatus] with a well-typed [EmploymentStatus] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun employmentStatus(employmentStatus: JsonField) = apply { + body.employmentStatus(employmentStatus) + } - /** The current title of the individual. */ - fun title(): Optional = Optional.ofNullable(title.getNullable("title")) + fun endDate(endDate: String?) = apply { body.endDate(endDate) } - /** Worker's compensation classification code for this employee */ - @JsonProperty("class_code") @ExcludeMissing fun _classCode(): JsonField = classCode + /** Alias for calling [Builder.endDate] with `endDate.orElse(null)`. */ + fun endDate(endDate: Optional) = endDate(endDate.getOrNull()) /** - * Custom fields for the individual. These are fields which are defined by the employer in - * the system. Custom fields are not currently supported for assisted connections. + * Sets [Builder.endDate] to an arbitrary JSON value. + * + * You should usually call [Builder.endDate] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ - @JsonProperty("custom_fields") - @ExcludeMissing - fun _customFields(): JsonField> = customFields - - /** The department object. */ - @JsonProperty("department") - @ExcludeMissing - fun _department(): JsonField = department - - /** The employment object. */ - @JsonProperty("employment") - @ExcludeMissing - fun _employment(): JsonField = employment + fun endDate(endDate: JsonField) = apply { body.endDate(endDate) } - /** The detailed employment status of the individual. */ - @JsonProperty("employment_status") - @ExcludeMissing - fun _employmentStatus(): JsonField = employmentStatus + /** The legal first name of the individual. */ + fun firstName(firstName: String?) = apply { body.firstName(firstName) } - @JsonProperty("end_date") @ExcludeMissing fun _endDate(): JsonField = endDate + /** Alias for calling [Builder.firstName] with `firstName.orElse(null)`. */ + fun firstName(firstName: Optional) = firstName(firstName.getOrNull()) - /** The legal first name of the individual. */ - @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun firstName(firstName: JsonField) = apply { body.firstName(firstName) } /** * The employee's income as reported by the provider. This may not always be annualized * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what * information the provider returns. */ - @JsonProperty("income") @ExcludeMissing fun _income(): JsonField = income - - /** The array of income history. */ - @JsonProperty("income_history") - @ExcludeMissing - fun _incomeHistory(): JsonField> = incomeHistory + fun income(income: Income?) = apply { body.income(income) } - /** `true` if the individual an an active employee or contractor at the company. */ - @JsonProperty("is_active") @ExcludeMissing fun _isActive(): JsonField = isActive + /** Alias for calling [Builder.income] with `income.orElse(null)`. */ + fun income(income: Optional) = income(income.getOrNull()) - /** The legal last name of the individual. */ - @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName + /** + * Sets [Builder.income] to an arbitrary JSON value. + * + * You should usually call [Builder.income] with a well-typed [Income] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun income(income: JsonField) = apply { body.income(income) } - @JsonProperty("latest_rehire_date") - @ExcludeMissing - fun _latestRehireDate(): JsonField = latestRehireDate + /** The array of income history. */ + fun incomeHistory(incomeHistory: List?) = apply { + body.incomeHistory(incomeHistory) + } - @JsonProperty("location") @ExcludeMissing fun _location(): JsonField = location + /** Alias for calling [Builder.incomeHistory] with `incomeHistory.orElse(null)`. */ + fun incomeHistory(incomeHistory: Optional>) = + incomeHistory(incomeHistory.getOrNull()) - /** The manager object representing the manager of the individual within the org. */ - @JsonProperty("manager") @ExcludeMissing fun _manager(): JsonField = manager + /** + * Sets [Builder.incomeHistory] to an arbitrary JSON value. + * + * You should usually call [Builder.incomeHistory] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun incomeHistory(incomeHistory: JsonField>) = apply { + body.incomeHistory(incomeHistory) + } - /** The legal middle name of the individual. */ - @JsonProperty("middle_name") - @ExcludeMissing - fun _middleName(): JsonField = middleName + /** + * Adds a single [Income] to [Builder.incomeHistory]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addIncomeHistory(incomeHistory: Income) = apply { body.addIncomeHistory(incomeHistory) } - /** The source system's unique employment identifier for this individual */ - @JsonProperty("source_id") @ExcludeMissing fun _sourceId(): JsonField = sourceId + /** `true` if the individual an an active employee or contractor at the company. */ + fun isActive(isActive: Boolean?) = apply { body.isActive(isActive) } - @JsonProperty("start_date") @ExcludeMissing fun _startDate(): JsonField = startDate + /** + * Alias for [Builder.isActive]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun isActive(isActive: Boolean) = isActive(isActive as Boolean?) - /** The current title of the individual. */ - @JsonProperty("title") @ExcludeMissing fun _title(): JsonField = title + /** Alias for calling [Builder.isActive] with `isActive.orElse(null)`. */ + fun isActive(isActive: Optional) = isActive(isActive.getOrNull()) - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** + * Sets [Builder.isActive] to an arbitrary JSON value. + * + * You should usually call [Builder.isActive] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun isActive(isActive: JsonField) = apply { body.isActive(isActive) } - private var validated: Boolean = false + /** The legal last name of the individual. */ + fun lastName(lastName: String?) = apply { body.lastName(lastName) } - fun validate(): EmploymentWithoutId = apply { - if (validated) { - return@apply - } + /** Alias for calling [Builder.lastName] with `lastName.orElse(null)`. */ + fun lastName(lastName: Optional) = lastName(lastName.getOrNull()) - classCode() - customFields().ifPresent { it.forEach { it.validate() } } - department().ifPresent { it.validate() } - employment().ifPresent { it.validate() } - employmentStatus() - endDate() - firstName() - income().ifPresent { it.validate() } - incomeHistory().ifPresent { it.forEach { it?.validate() } } - isActive() - lastName() - latestRehireDate() - location().ifPresent { it.validate() } - manager().ifPresent { it.validate() } - middleName() - sourceId() - startDate() - title() - validated = true - } + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun lastName(lastName: JsonField) = apply { body.lastName(lastName) } - fun toBuilder() = Builder().from(this) + fun latestRehireDate(latestRehireDate: String?) = apply { + body.latestRehireDate(latestRehireDate) + } - companion object { + /** Alias for calling [Builder.latestRehireDate] with `latestRehireDate.orElse(null)`. */ + fun latestRehireDate(latestRehireDate: Optional) = + latestRehireDate(latestRehireDate.getOrNull()) - @JvmStatic fun builder() = Builder() + /** + * Sets [Builder.latestRehireDate] to an arbitrary JSON value. + * + * You should usually call [Builder.latestRehireDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun latestRehireDate(latestRehireDate: JsonField) = apply { + body.latestRehireDate(latestRehireDate) } - /** A builder for [EmploymentWithoutId]. */ - class Builder internal constructor() { + fun location(location: Location?) = apply { body.location(location) } - private var classCode: JsonField = JsonMissing.of() - private var customFields: JsonField>? = null - private var department: JsonField = JsonMissing.of() - private var employment: JsonField = JsonMissing.of() - private var employmentStatus: JsonField = JsonMissing.of() - private var endDate: JsonField = JsonMissing.of() - private var firstName: JsonField = JsonMissing.of() - private var income: JsonField = JsonMissing.of() - private var incomeHistory: JsonField>? = null - private var isActive: JsonField = JsonMissing.of() - private var lastName: JsonField = JsonMissing.of() - private var latestRehireDate: JsonField = JsonMissing.of() - private var location: JsonField = JsonMissing.of() - private var manager: JsonField = JsonMissing.of() - private var middleName: JsonField = JsonMissing.of() - private var sourceId: JsonField = JsonMissing.of() - private var startDate: JsonField = JsonMissing.of() - private var title: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + /** Alias for calling [Builder.location] with `location.orElse(null)`. */ + fun location(location: Optional) = location(location.getOrNull()) - @JvmSynthetic - internal fun from(employmentWithoutId: EmploymentWithoutId) = apply { - classCode = employmentWithoutId.classCode - customFields = employmentWithoutId.customFields.map { it.toMutableList() } - department = employmentWithoutId.department - employment = employmentWithoutId.employment - employmentStatus = employmentWithoutId.employmentStatus - endDate = employmentWithoutId.endDate - firstName = employmentWithoutId.firstName - income = employmentWithoutId.income - incomeHistory = employmentWithoutId.incomeHistory.map { it.toMutableList() } - isActive = employmentWithoutId.isActive - lastName = employmentWithoutId.lastName - latestRehireDate = employmentWithoutId.latestRehireDate - location = employmentWithoutId.location - manager = employmentWithoutId.manager - middleName = employmentWithoutId.middleName - sourceId = employmentWithoutId.sourceId - startDate = employmentWithoutId.startDate - title = employmentWithoutId.title - additionalProperties = employmentWithoutId.additionalProperties.toMutableMap() - } + /** + * Sets [Builder.location] to an arbitrary JSON value. + * + * You should usually call [Builder.location] with a well-typed [Location] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun location(location: JsonField) = apply { body.location(location) } - /** Worker's compensation classification code for this employee */ - fun classCode(classCode: String?) = classCode(JsonField.ofNullable(classCode)) + /** The manager object representing the manager of the individual within the org. */ + fun manager(manager: Manager?) = apply { body.manager(manager) } - /** Worker's compensation classification code for this employee */ - fun classCode(classCode: Optional) = classCode(classCode.orElse(null)) + /** Alias for calling [Builder.manager] with `manager.orElse(null)`. */ + fun manager(manager: Optional) = manager(manager.getOrNull()) - /** Worker's compensation classification code for this employee */ - fun classCode(classCode: JsonField) = apply { this.classCode = classCode } + /** + * Sets [Builder.manager] to an arbitrary JSON value. + * + * You should usually call [Builder.manager] with a well-typed [Manager] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun manager(manager: JsonField) = apply { body.manager(manager) } - /** - * Custom fields for the individual. These are fields which are defined by the employer - * in the system. Custom fields are not currently supported for assisted connections. - */ - fun customFields(customFields: List) = - customFields(JsonField.of(customFields)) + /** The legal middle name of the individual. */ + fun middleName(middleName: String?) = apply { body.middleName(middleName) } - /** - * Custom fields for the individual. These are fields which are defined by the employer - * in the system. Custom fields are not currently supported for assisted connections. - */ - fun customFields(customFields: JsonField>) = apply { - this.customFields = customFields.map { it.toMutableList() } - } + /** Alias for calling [Builder.middleName] with `middleName.orElse(null)`. */ + fun middleName(middleName: Optional) = middleName(middleName.getOrNull()) - /** - * Custom fields for the individual. These are fields which are defined by the employer - * in the system. Custom fields are not currently supported for assisted connections. - */ - fun addCustomField(customField: CustomField) = apply { - customFields = - (customFields ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(customField) - } - } + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun middleName(middleName: JsonField) = apply { body.middleName(middleName) } - /** The department object. */ - fun department(department: Department?) = department(JsonField.ofNullable(department)) + /** The source system's unique employment identifier for this individual */ + fun sourceId(sourceId: String) = apply { body.sourceId(sourceId) } - /** The department object. */ - fun department(department: Optional) = department(department.orElse(null)) + /** + * Sets [Builder.sourceId] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun sourceId(sourceId: JsonField) = apply { body.sourceId(sourceId) } - /** The department object. */ - fun department(department: JsonField) = apply { - this.department = department - } + fun startDate(startDate: String?) = apply { body.startDate(startDate) } - /** The employment object. */ - fun employment(employment: Employment?) = employment(JsonField.ofNullable(employment)) + /** Alias for calling [Builder.startDate] with `startDate.orElse(null)`. */ + fun startDate(startDate: Optional) = startDate(startDate.getOrNull()) - /** The employment object. */ - fun employment(employment: Optional) = employment(employment.orElse(null)) + /** + * Sets [Builder.startDate] to an arbitrary JSON value. + * + * You should usually call [Builder.startDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun startDate(startDate: JsonField) = apply { body.startDate(startDate) } - /** The employment object. */ - fun employment(employment: JsonField) = apply { - this.employment = employment - } + /** The current title of the individual. */ + fun title(title: String?) = apply { body.title(title) } - /** The detailed employment status of the individual. */ - fun employmentStatus(employmentStatus: EmploymentStatus?) = - employmentStatus(JsonField.ofNullable(employmentStatus)) + /** Alias for calling [Builder.title] with `title.orElse(null)`. */ + fun title(title: Optional) = title(title.getOrNull()) - /** The detailed employment status of the individual. */ - fun employmentStatus(employmentStatus: Optional) = - employmentStatus(employmentStatus.orElse(null)) + /** + * Sets [Builder.title] to an arbitrary JSON value. + * + * You should usually call [Builder.title] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun title(title: JsonField) = apply { body.title(title) } - /** The detailed employment status of the individual. */ - fun employmentStatus(employmentStatus: JsonField) = apply { - this.employmentStatus = employmentStatus + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - fun endDate(endDate: String?) = endDate(JsonField.ofNullable(endDate)) + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun endDate(endDate: Optional) = endDate(endDate.orElse(null)) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - fun endDate(endDate: JsonField) = apply { this.endDate = endDate } + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** The legal first name of the individual. */ - fun firstName(firstName: String?) = firstName(JsonField.ofNullable(firstName)) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** The legal first name of the individual. */ - fun firstName(firstName: Optional) = firstName(firstName.orElse(null)) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** The legal first name of the individual. */ - fun firstName(firstName: JsonField) = apply { this.firstName = firstName } + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. - */ - fun income(income: Income?) = income(JsonField.ofNullable(income)) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. - */ - fun income(income: Optional) = income(income.orElse(null)) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. - */ - fun income(income: JsonField) = apply { this.income = income } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** The array of income history. */ - fun incomeHistory(incomeHistory: List?) = - incomeHistory(JsonField.ofNullable(incomeHistory)) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** The array of income history. */ - fun incomeHistory(incomeHistory: Optional>) = - incomeHistory(incomeHistory.orElse(null)) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** The array of income history. */ - fun incomeHistory(incomeHistory: JsonField>) = apply { - this.incomeHistory = incomeHistory.map { it.toMutableList() } - } + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** The array of income history. */ - fun addIncomeHistory(incomeHistory: Income) = apply { - this.incomeHistory = - (this.incomeHistory ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(incomeHistory) - } - } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - /** `true` if the individual an an active employee or contractor at the company. */ - fun isActive(isActive: Boolean?) = isActive(JsonField.ofNullable(isActive)) + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - /** `true` if the individual an an active employee or contractor at the company. */ - fun isActive(isActive: Boolean) = isActive(isActive as Boolean?) + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - /** `true` if the individual an an active employee or contractor at the company. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun isActive(isActive: Optional) = isActive(isActive.orElse(null) as Boolean?) + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - /** `true` if the individual an an active employee or contractor at the company. */ - fun isActive(isActive: JsonField) = apply { this.isActive = isActive } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - /** The legal last name of the individual. */ - fun lastName(lastName: String?) = lastName(JsonField.ofNullable(lastName)) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - /** The legal last name of the individual. */ - fun lastName(lastName: Optional) = lastName(lastName.orElse(null)) + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - /** The legal last name of the individual. */ - fun lastName(lastName: JsonField) = apply { this.lastName = lastName } + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } - fun latestRehireDate(latestRehireDate: String?) = - latestRehireDate(JsonField.ofNullable(latestRehireDate)) + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - fun latestRehireDate(latestRehireDate: Optional) = - latestRehireDate(latestRehireDate.orElse(null)) + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun latestRehireDate(latestRehireDate: JsonField) = apply { - this.latestRehireDate = latestRehireDate + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - fun location(location: Location?) = location(JsonField.ofNullable(location)) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - fun location(location: Optional) = location(location.orElse(null)) + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } - fun location(location: JsonField) = apply { this.location = location } + /** + * Returns an immutable instance of [SandboxEmploymentUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .individualId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SandboxEmploymentUpdateParams = + SandboxEmploymentUpdateParams( + checkRequired("individualId", individualId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } - /** The manager object representing the manager of the individual within the org. */ - fun manager(manager: Manager?) = manager(JsonField.ofNullable(manager)) + fun _body(): EmploymentWithoutId = body - /** The manager object representing the manager of the individual within the org. */ - fun manager(manager: Optional) = manager(manager.orElse(null)) + fun _pathParam(index: Int): String = + when (index) { + 0 -> individualId + else -> "" + } - /** The manager object representing the manager of the individual within the org. */ - fun manager(manager: JsonField) = apply { this.manager = manager } + override fun _headers(): Headers = additionalHeaders - /** The legal middle name of the individual. */ - fun middleName(middleName: String?) = middleName(JsonField.ofNullable(middleName)) + override fun _queryParams(): QueryParams = additionalQueryParams - /** The legal middle name of the individual. */ - fun middleName(middleName: Optional) = middleName(middleName.orElse(null)) + class EmploymentWithoutId + private constructor( + private val classCode: JsonField, + private val customFields: JsonField>, + private val department: JsonField, + private val employment: JsonField, + private val employmentStatus: JsonField, + private val endDate: JsonField, + private val firstName: JsonField, + private val income: JsonField, + private val incomeHistory: JsonField>, + private val isActive: JsonField, + private val lastName: JsonField, + private val latestRehireDate: JsonField, + private val location: JsonField, + private val manager: JsonField, + private val middleName: JsonField, + private val sourceId: JsonField, + private val startDate: JsonField, + private val title: JsonField, + private val additionalProperties: MutableMap, + ) { - /** The legal middle name of the individual. */ - fun middleName(middleName: JsonField) = apply { this.middleName = middleName } + @JsonCreator + private constructor( + @JsonProperty("class_code") + @ExcludeMissing + classCode: JsonField = JsonMissing.of(), + @JsonProperty("custom_fields") + @ExcludeMissing + customFields: JsonField> = JsonMissing.of(), + @JsonProperty("department") + @ExcludeMissing + department: JsonField = JsonMissing.of(), + @JsonProperty("employment") + @ExcludeMissing + employment: JsonField = JsonMissing.of(), + @JsonProperty("employment_status") + @ExcludeMissing + employmentStatus: JsonField = JsonMissing.of(), + @JsonProperty("end_date") @ExcludeMissing endDate: JsonField = JsonMissing.of(), + @JsonProperty("first_name") + @ExcludeMissing + firstName: JsonField = JsonMissing.of(), + @JsonProperty("income") @ExcludeMissing income: JsonField = JsonMissing.of(), + @JsonProperty("income_history") + @ExcludeMissing + incomeHistory: JsonField> = JsonMissing.of(), + @JsonProperty("is_active") + @ExcludeMissing + isActive: JsonField = JsonMissing.of(), + @JsonProperty("last_name") + @ExcludeMissing + lastName: JsonField = JsonMissing.of(), + @JsonProperty("latest_rehire_date") + @ExcludeMissing + latestRehireDate: JsonField = JsonMissing.of(), + @JsonProperty("location") + @ExcludeMissing + location: JsonField = JsonMissing.of(), + @JsonProperty("manager") @ExcludeMissing manager: JsonField = JsonMissing.of(), + @JsonProperty("middle_name") + @ExcludeMissing + middleName: JsonField = JsonMissing.of(), + @JsonProperty("source_id") + @ExcludeMissing + sourceId: JsonField = JsonMissing.of(), + @JsonProperty("start_date") + @ExcludeMissing + startDate: JsonField = JsonMissing.of(), + @JsonProperty("title") @ExcludeMissing title: JsonField = JsonMissing.of(), + ) : this( + classCode, + customFields, + department, + employment, + employmentStatus, + endDate, + firstName, + income, + incomeHistory, + isActive, + lastName, + latestRehireDate, + location, + manager, + middleName, + sourceId, + startDate, + title, + mutableMapOf(), + ) - /** The source system's unique employment identifier for this individual */ - fun sourceId(sourceId: String) = sourceId(JsonField.of(sourceId)) + /** + * Worker's compensation classification code for this employee + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun classCode(): Optional = classCode.getOptional("class_code") - /** The source system's unique employment identifier for this individual */ - fun sourceId(sourceId: JsonField) = apply { this.sourceId = sourceId } + /** + * Custom fields for the individual. These are fields which are defined by the employer in + * the system. Custom fields are not currently supported for assisted connections. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun customFields(): Optional> = customFields.getOptional("custom_fields") - fun startDate(startDate: String?) = startDate(JsonField.ofNullable(startDate)) + /** + * The department object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun department(): Optional = department.getOptional("department") - fun startDate(startDate: Optional) = startDate(startDate.orElse(null)) + /** + * The employment object. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun employment(): Optional = employment.getOptional("employment") - fun startDate(startDate: JsonField) = apply { this.startDate = startDate } + /** + * The detailed employment status of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun employmentStatus(): Optional = + employmentStatus.getOptional("employment_status") - /** The current title of the individual. */ - fun title(title: String?) = title(JsonField.ofNullable(title)) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun endDate(): Optional = endDate.getOptional("end_date") - /** The current title of the individual. */ - fun title(title: Optional) = title(title.orElse(null)) + /** + * The legal first name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") - /** The current title of the individual. */ - fun title(title: JsonField) = apply { this.title = title } + /** + * The employee's income as reported by the provider. This may not always be annualized + * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what + * information the provider returns. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun income(): Optional = income.getOptional("income") - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + /** + * The array of income history. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun incomeHistory(): Optional> = incomeHistory.getOptional("income_history") - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + /** + * `true` if the individual an an active employee or contractor at the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isActive(): Optional = isActive.getOptional("is_active") - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + /** + * The legal last name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun latestRehireDate(): Optional = + latestRehireDate.getOptional("latest_rehire_date") - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun location(): Optional = location.getOptional("location") - fun build(): EmploymentWithoutId = - EmploymentWithoutId( - classCode, - (customFields ?: JsonMissing.of()).map { it.toImmutable() }, - department, - employment, - employmentStatus, - endDate, - firstName, - income, - (incomeHistory ?: JsonMissing.of()).map { it.toImmutable() }, - isActive, - lastName, - latestRehireDate, - location, - manager, - middleName, - sourceId, - startDate, - title, - additionalProperties.toImmutable(), - ) - } + /** + * The manager object representing the manager of the individual within the org. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun manager(): Optional = manager.getOptional("manager") - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** + * The legal middle name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") - return /* spotless:off */ other is EmploymentWithoutId && classCode == other.classCode && customFields == other.customFields && department == other.department && employment == other.employment && employmentStatus == other.employmentStatus && endDate == other.endDate && firstName == other.firstName && income == other.income && incomeHistory == other.incomeHistory && isActive == other.isActive && lastName == other.lastName && latestRehireDate == other.latestRehireDate && location == other.location && manager == other.manager && middleName == other.middleName && sourceId == other.sourceId && startDate == other.startDate && title == other.title && additionalProperties == other.additionalProperties /* spotless:on */ - } + /** + * The source system's unique employment identifier for this individual + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun sourceId(): Optional = sourceId.getOptional("source_id") - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(classCode, customFields, department, employment, employmentStatus, endDate, firstName, income, incomeHistory, isActive, lastName, latestRehireDate, location, manager, middleName, sourceId, startDate, title, additionalProperties) } - /* spotless:on */ + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun startDate(): Optional = startDate.getOptional("start_date") - override fun hashCode(): Int = hashCode + /** + * The current title of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun title(): Optional = title.getOptional("title") - override fun toString() = - "EmploymentWithoutId{classCode=$classCode, customFields=$customFields, department=$department, employment=$employment, employmentStatus=$employmentStatus, endDate=$endDate, firstName=$firstName, income=$income, incomeHistory=$incomeHistory, isActive=$isActive, lastName=$lastName, latestRehireDate=$latestRehireDate, location=$location, manager=$manager, middleName=$middleName, sourceId=$sourceId, startDate=$startDate, title=$title, additionalProperties=$additionalProperties}" - } + /** + * Returns the raw JSON value of [classCode]. + * + * Unlike [classCode], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("class_code") @ExcludeMissing fun _classCode(): JsonField = classCode - fun toBuilder() = Builder().from(this) + /** + * Returns the raw JSON value of [customFields]. + * + * Unlike [customFields], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("custom_fields") + @ExcludeMissing + fun _customFields(): JsonField> = customFields - companion object { + /** + * Returns the raw JSON value of [department]. + * + * Unlike [department], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("department") + @ExcludeMissing + fun _department(): JsonField = department - @JvmStatic fun builder() = Builder() - } + /** + * Returns the raw JSON value of [employment]. + * + * Unlike [employment], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("employment") + @ExcludeMissing + fun _employment(): JsonField = employment - /** A builder for [SandboxEmploymentUpdateParams]. */ - @NoAutoDetect - class Builder internal constructor() { + /** + * Returns the raw JSON value of [employmentStatus]. + * + * Unlike [employmentStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("employment_status") + @ExcludeMissing + fun _employmentStatus(): JsonField = employmentStatus - private var individualId: String? = null - private var body: EmploymentWithoutId.Builder = EmploymentWithoutId.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + /** + * Returns the raw JSON value of [endDate]. + * + * Unlike [endDate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("end_date") @ExcludeMissing fun _endDate(): JsonField = endDate - @JvmSynthetic - internal fun from(sandboxEmploymentUpdateParams: SandboxEmploymentUpdateParams) = apply { - individualId = sandboxEmploymentUpdateParams.individualId - body = sandboxEmploymentUpdateParams.body.toBuilder() - additionalHeaders = sandboxEmploymentUpdateParams.additionalHeaders.toBuilder() - additionalQueryParams = sandboxEmploymentUpdateParams.additionalQueryParams.toBuilder() - } + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName + + /** + * Returns the raw JSON value of [income]. + * + * Unlike [income], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("income") @ExcludeMissing fun _income(): JsonField = income - fun individualId(individualId: String) = apply { this.individualId = individualId } + /** + * Returns the raw JSON value of [incomeHistory]. + * + * Unlike [incomeHistory], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("income_history") + @ExcludeMissing + fun _incomeHistory(): JsonField> = incomeHistory - /** Worker's compensation classification code for this employee */ - fun classCode(classCode: String?) = apply { body.classCode(classCode) } + /** + * Returns the raw JSON value of [isActive]. + * + * Unlike [isActive], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("is_active") @ExcludeMissing fun _isActive(): JsonField = isActive - /** Worker's compensation classification code for this employee */ - fun classCode(classCode: Optional) = classCode(classCode.orElse(null)) + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName - /** Worker's compensation classification code for this employee */ - fun classCode(classCode: JsonField) = apply { body.classCode(classCode) } + /** + * Returns the raw JSON value of [latestRehireDate]. + * + * Unlike [latestRehireDate], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("latest_rehire_date") + @ExcludeMissing + fun _latestRehireDate(): JsonField = latestRehireDate /** - * Custom fields for the individual. These are fields which are defined by the employer in - * the system. Custom fields are not currently supported for assisted connections. + * Returns the raw JSON value of [location]. + * + * Unlike [location], this method doesn't throw if the JSON field has an unexpected type. */ - fun customFields(customFields: List) = apply { - body.customFields(customFields) - } + @JsonProperty("location") @ExcludeMissing fun _location(): JsonField = location /** - * Custom fields for the individual. These are fields which are defined by the employer in - * the system. Custom fields are not currently supported for assisted connections. + * Returns the raw JSON value of [manager]. + * + * Unlike [manager], this method doesn't throw if the JSON field has an unexpected type. */ - fun customFields(customFields: JsonField>) = apply { - body.customFields(customFields) - } + @JsonProperty("manager") @ExcludeMissing fun _manager(): JsonField = manager /** - * Custom fields for the individual. These are fields which are defined by the employer in - * the system. Custom fields are not currently supported for assisted connections. + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an unexpected type. */ - fun addCustomField(customField: CustomField) = apply { body.addCustomField(customField) } + @JsonProperty("middle_name") + @ExcludeMissing + fun _middleName(): JsonField = middleName - /** The department object. */ - fun department(department: Department?) = apply { body.department(department) } + /** + * Returns the raw JSON value of [sourceId]. + * + * Unlike [sourceId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("source_id") @ExcludeMissing fun _sourceId(): JsonField = sourceId - /** The department object. */ - fun department(department: Optional) = department(department.orElse(null)) + /** + * Returns the raw JSON value of [startDate]. + * + * Unlike [startDate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("start_date") @ExcludeMissing fun _startDate(): JsonField = startDate - /** The department object. */ - fun department(department: JsonField) = apply { body.department(department) } + /** + * Returns the raw JSON value of [title]. + * + * Unlike [title], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("title") @ExcludeMissing fun _title(): JsonField = title - /** The employment object. */ - fun employment(employment: Employment?) = apply { body.employment(employment) } + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } - /** The employment object. */ - fun employment(employment: Optional) = employment(employment.orElse(null)) + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - /** The employment object. */ - fun employment(employment: JsonField) = apply { body.employment(employment) } + fun toBuilder() = Builder().from(this) - /** The detailed employment status of the individual. */ - fun employmentStatus(employmentStatus: EmploymentStatus?) = apply { - body.employmentStatus(employmentStatus) + companion object { + + /** Returns a mutable builder for constructing an instance of [EmploymentWithoutId]. */ + @JvmStatic fun builder() = Builder() } - /** The detailed employment status of the individual. */ - fun employmentStatus(employmentStatus: Optional) = - employmentStatus(employmentStatus.orElse(null)) + /** A builder for [EmploymentWithoutId]. */ + class Builder internal constructor() { - /** The detailed employment status of the individual. */ - fun employmentStatus(employmentStatus: JsonField) = apply { - body.employmentStatus(employmentStatus) - } + private var classCode: JsonField = JsonMissing.of() + private var customFields: JsonField>? = null + private var department: JsonField = JsonMissing.of() + private var employment: JsonField = JsonMissing.of() + private var employmentStatus: JsonField = JsonMissing.of() + private var endDate: JsonField = JsonMissing.of() + private var firstName: JsonField = JsonMissing.of() + private var income: JsonField = JsonMissing.of() + private var incomeHistory: JsonField>? = null + private var isActive: JsonField = JsonMissing.of() + private var lastName: JsonField = JsonMissing.of() + private var latestRehireDate: JsonField = JsonMissing.of() + private var location: JsonField = JsonMissing.of() + private var manager: JsonField = JsonMissing.of() + private var middleName: JsonField = JsonMissing.of() + private var sourceId: JsonField = JsonMissing.of() + private var startDate: JsonField = JsonMissing.of() + private var title: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() - fun endDate(endDate: String?) = apply { body.endDate(endDate) } + @JvmSynthetic + internal fun from(employmentWithoutId: EmploymentWithoutId) = apply { + classCode = employmentWithoutId.classCode + customFields = employmentWithoutId.customFields.map { it.toMutableList() } + department = employmentWithoutId.department + employment = employmentWithoutId.employment + employmentStatus = employmentWithoutId.employmentStatus + endDate = employmentWithoutId.endDate + firstName = employmentWithoutId.firstName + income = employmentWithoutId.income + incomeHistory = employmentWithoutId.incomeHistory.map { it.toMutableList() } + isActive = employmentWithoutId.isActive + lastName = employmentWithoutId.lastName + latestRehireDate = employmentWithoutId.latestRehireDate + location = employmentWithoutId.location + manager = employmentWithoutId.manager + middleName = employmentWithoutId.middleName + sourceId = employmentWithoutId.sourceId + startDate = employmentWithoutId.startDate + title = employmentWithoutId.title + additionalProperties = employmentWithoutId.additionalProperties.toMutableMap() + } - fun endDate(endDate: Optional) = endDate(endDate.orElse(null)) + /** Worker's compensation classification code for this employee */ + fun classCode(classCode: String?) = classCode(JsonField.ofNullable(classCode)) - fun endDate(endDate: JsonField) = apply { body.endDate(endDate) } + /** Alias for calling [Builder.classCode] with `classCode.orElse(null)`. */ + fun classCode(classCode: Optional) = classCode(classCode.getOrNull()) - /** The legal first name of the individual. */ - fun firstName(firstName: String?) = apply { body.firstName(firstName) } + /** + * Sets [Builder.classCode] to an arbitrary JSON value. + * + * You should usually call [Builder.classCode] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun classCode(classCode: JsonField) = apply { this.classCode = classCode } - /** The legal first name of the individual. */ - fun firstName(firstName: Optional) = firstName(firstName.orElse(null)) + /** + * Custom fields for the individual. These are fields which are defined by the employer + * in the system. Custom fields are not currently supported for assisted connections. + */ + fun customFields(customFields: List) = + customFields(JsonField.of(customFields)) - /** The legal first name of the individual. */ - fun firstName(firstName: JsonField) = apply { body.firstName(firstName) } + /** + * Sets [Builder.customFields] to an arbitrary JSON value. + * + * You should usually call [Builder.customFields] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun customFields(customFields: JsonField>) = apply { + this.customFields = customFields.map { it.toMutableList() } + } - /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. - */ - fun income(income: Income?) = apply { body.income(income) } + /** + * Adds a single [CustomField] to [customFields]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addCustomField(customField: CustomField) = apply { + customFields = + (customFields ?: JsonField.of(mutableListOf())).also { + checkKnown("customFields", it).add(customField) + } + } - /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. - */ - fun income(income: Optional) = income(income.orElse(null)) + /** The department object. */ + fun department(department: Department?) = department(JsonField.ofNullable(department)) - /** - * The employee's income as reported by the provider. This may not always be annualized - * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what - * information the provider returns. - */ - fun income(income: JsonField) = apply { body.income(income) } + /** Alias for calling [Builder.department] with `department.orElse(null)`. */ + fun department(department: Optional) = department(department.getOrNull()) - /** The array of income history. */ - fun incomeHistory(incomeHistory: List?) = apply { - body.incomeHistory(incomeHistory) - } + /** + * Sets [Builder.department] to an arbitrary JSON value. + * + * You should usually call [Builder.department] with a well-typed [Department] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun department(department: JsonField) = apply { + this.department = department + } - /** The array of income history. */ - fun incomeHistory(incomeHistory: Optional>) = - incomeHistory(incomeHistory.orElse(null)) + /** The employment object. */ + fun employment(employment: Employment?) = employment(JsonField.ofNullable(employment)) - /** The array of income history. */ - fun incomeHistory(incomeHistory: JsonField>) = apply { - body.incomeHistory(incomeHistory) - } + /** Alias for calling [Builder.employment] with `employment.orElse(null)`. */ + fun employment(employment: Optional) = employment(employment.getOrNull()) - /** The array of income history. */ - fun addIncomeHistory(incomeHistory: Income) = apply { body.addIncomeHistory(incomeHistory) } + /** + * Sets [Builder.employment] to an arbitrary JSON value. + * + * You should usually call [Builder.employment] with a well-typed [Employment] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun employment(employment: JsonField) = apply { + this.employment = employment + } - /** `true` if the individual an an active employee or contractor at the company. */ - fun isActive(isActive: Boolean?) = apply { body.isActive(isActive) } + /** The detailed employment status of the individual. */ + fun employmentStatus(employmentStatus: EmploymentStatus?) = + employmentStatus(JsonField.ofNullable(employmentStatus)) - /** `true` if the individual an an active employee or contractor at the company. */ - fun isActive(isActive: Boolean) = isActive(isActive as Boolean?) + /** + * Alias for calling [Builder.employmentStatus] with `employmentStatus.orElse(null)`. + */ + fun employmentStatus(employmentStatus: Optional) = + employmentStatus(employmentStatus.getOrNull()) - /** `true` if the individual an an active employee or contractor at the company. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun isActive(isActive: Optional) = isActive(isActive.orElse(null) as Boolean?) + /** + * Sets [Builder.employmentStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.employmentStatus] with a well-typed + * [EmploymentStatus] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun employmentStatus(employmentStatus: JsonField) = apply { + this.employmentStatus = employmentStatus + } - /** `true` if the individual an an active employee or contractor at the company. */ - fun isActive(isActive: JsonField) = apply { body.isActive(isActive) } + fun endDate(endDate: String?) = endDate(JsonField.ofNullable(endDate)) - /** The legal last name of the individual. */ - fun lastName(lastName: String?) = apply { body.lastName(lastName) } + /** Alias for calling [Builder.endDate] with `endDate.orElse(null)`. */ + fun endDate(endDate: Optional) = endDate(endDate.getOrNull()) - /** The legal last name of the individual. */ - fun lastName(lastName: Optional) = lastName(lastName.orElse(null)) + /** + * Sets [Builder.endDate] to an arbitrary JSON value. + * + * You should usually call [Builder.endDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun endDate(endDate: JsonField) = apply { this.endDate = endDate } - /** The legal last name of the individual. */ - fun lastName(lastName: JsonField) = apply { body.lastName(lastName) } + /** The legal first name of the individual. */ + fun firstName(firstName: String?) = firstName(JsonField.ofNullable(firstName)) - fun latestRehireDate(latestRehireDate: String?) = apply { - body.latestRehireDate(latestRehireDate) - } + /** Alias for calling [Builder.firstName] with `firstName.orElse(null)`. */ + fun firstName(firstName: Optional) = firstName(firstName.getOrNull()) - fun latestRehireDate(latestRehireDate: Optional) = - latestRehireDate(latestRehireDate.orElse(null)) + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun firstName(firstName: JsonField) = apply { this.firstName = firstName } - fun latestRehireDate(latestRehireDate: JsonField) = apply { - body.latestRehireDate(latestRehireDate) - } + /** + * The employee's income as reported by the provider. This may not always be annualized + * income, but may be in units of bi-weekly, semi-monthly, daily, etc, depending on what + * information the provider returns. + */ + fun income(income: Income?) = income(JsonField.ofNullable(income)) - fun location(location: Location?) = apply { body.location(location) } + /** Alias for calling [Builder.income] with `income.orElse(null)`. */ + fun income(income: Optional) = income(income.getOrNull()) + + /** + * Sets [Builder.income] to an arbitrary JSON value. + * + * You should usually call [Builder.income] with a well-typed [Income] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun income(income: JsonField) = apply { this.income = income } - fun location(location: Optional) = location(location.orElse(null)) + /** The array of income history. */ + fun incomeHistory(incomeHistory: List?) = + incomeHistory(JsonField.ofNullable(incomeHistory)) - fun location(location: JsonField) = apply { body.location(location) } + /** Alias for calling [Builder.incomeHistory] with `incomeHistory.orElse(null)`. */ + fun incomeHistory(incomeHistory: Optional>) = + incomeHistory(incomeHistory.getOrNull()) - /** The manager object representing the manager of the individual within the org. */ - fun manager(manager: Manager?) = apply { body.manager(manager) } + /** + * Sets [Builder.incomeHistory] to an arbitrary JSON value. + * + * You should usually call [Builder.incomeHistory] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun incomeHistory(incomeHistory: JsonField>) = apply { + this.incomeHistory = incomeHistory.map { it.toMutableList() } + } - /** The manager object representing the manager of the individual within the org. */ - fun manager(manager: Optional) = manager(manager.orElse(null)) + /** + * Adds a single [Income] to [Builder.incomeHistory]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addIncomeHistory(incomeHistory: Income) = apply { + this.incomeHistory = + (this.incomeHistory ?: JsonField.of(mutableListOf())).also { + checkKnown("incomeHistory", it).add(incomeHistory) + } + } - /** The manager object representing the manager of the individual within the org. */ - fun manager(manager: JsonField) = apply { body.manager(manager) } + /** `true` if the individual an an active employee or contractor at the company. */ + fun isActive(isActive: Boolean?) = isActive(JsonField.ofNullable(isActive)) - /** The legal middle name of the individual. */ - fun middleName(middleName: String?) = apply { body.middleName(middleName) } + /** + * Alias for [Builder.isActive]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun isActive(isActive: Boolean) = isActive(isActive as Boolean?) - /** The legal middle name of the individual. */ - fun middleName(middleName: Optional) = middleName(middleName.orElse(null)) + /** Alias for calling [Builder.isActive] with `isActive.orElse(null)`. */ + fun isActive(isActive: Optional) = isActive(isActive.getOrNull()) - /** The legal middle name of the individual. */ - fun middleName(middleName: JsonField) = apply { body.middleName(middleName) } + /** + * Sets [Builder.isActive] to an arbitrary JSON value. + * + * You should usually call [Builder.isActive] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun isActive(isActive: JsonField) = apply { this.isActive = isActive } - /** The source system's unique employment identifier for this individual */ - fun sourceId(sourceId: String) = apply { body.sourceId(sourceId) } + /** The legal last name of the individual. */ + fun lastName(lastName: String?) = lastName(JsonField.ofNullable(lastName)) - /** The source system's unique employment identifier for this individual */ - fun sourceId(sourceId: JsonField) = apply { body.sourceId(sourceId) } + /** Alias for calling [Builder.lastName] with `lastName.orElse(null)`. */ + fun lastName(lastName: Optional) = lastName(lastName.getOrNull()) - fun startDate(startDate: String?) = apply { body.startDate(startDate) } + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun lastName(lastName: JsonField) = apply { this.lastName = lastName } - fun startDate(startDate: Optional) = startDate(startDate.orElse(null)) + fun latestRehireDate(latestRehireDate: String?) = + latestRehireDate(JsonField.ofNullable(latestRehireDate)) - fun startDate(startDate: JsonField) = apply { body.startDate(startDate) } + /** + * Alias for calling [Builder.latestRehireDate] with `latestRehireDate.orElse(null)`. + */ + fun latestRehireDate(latestRehireDate: Optional) = + latestRehireDate(latestRehireDate.getOrNull()) - /** The current title of the individual. */ - fun title(title: String?) = apply { body.title(title) } + /** + * Sets [Builder.latestRehireDate] to an arbitrary JSON value. + * + * You should usually call [Builder.latestRehireDate] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun latestRehireDate(latestRehireDate: JsonField) = apply { + this.latestRehireDate = latestRehireDate + } - /** The current title of the individual. */ - fun title(title: Optional) = title(title.orElse(null)) + fun location(location: Location?) = location(JsonField.ofNullable(location)) - /** The current title of the individual. */ - fun title(title: JsonField) = apply { body.title(title) } + /** Alias for calling [Builder.location] with `location.orElse(null)`. */ + fun location(location: Optional) = location(location.getOrNull()) - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } + /** + * Sets [Builder.location] to an arbitrary JSON value. + * + * You should usually call [Builder.location] with a well-typed [Location] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun location(location: JsonField) = apply { this.location = location } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + /** The manager object representing the manager of the individual within the org. */ + fun manager(manager: Manager?) = manager(JsonField.ofNullable(manager)) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } + /** Alias for calling [Builder.manager] with `manager.orElse(null)`. */ + fun manager(manager: Optional) = manager(manager.getOrNull()) - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** + * Sets [Builder.manager] to an arbitrary JSON value. + * + * You should usually call [Builder.manager] with a well-typed [Manager] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun manager(manager: JsonField) = apply { this.manager = manager } - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** The legal middle name of the individual. */ + fun middleName(middleName: String?) = middleName(JsonField.ofNullable(middleName)) - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Alias for calling [Builder.middleName] with `middleName.orElse(null)`. */ + fun middleName(middleName: Optional) = middleName(middleName.getOrNull()) - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun middleName(middleName: JsonField) = apply { this.middleName = middleName } - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** The source system's unique employment identifier for this individual */ + fun sourceId(sourceId: String) = sourceId(JsonField.of(sourceId)) - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Sets [Builder.sourceId] to an arbitrary JSON value. + * + * You should usually call [Builder.sourceId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sourceId(sourceId: JsonField) = apply { this.sourceId = sourceId } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + fun startDate(startDate: String?) = startDate(JsonField.ofNullable(startDate)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.startDate] with `startDate.orElse(null)`. */ + fun startDate(startDate: Optional) = startDate(startDate.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.startDate] to an arbitrary JSON value. + * + * You should usually call [Builder.startDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun startDate(startDate: JsonField) = apply { this.startDate = startDate } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + /** The current title of the individual. */ + fun title(title: String?) = title(JsonField.ofNullable(title)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.title] with `title.orElse(null)`. */ + fun title(title: Optional) = title(title.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.title] to an arbitrary JSON value. + * + * You should usually call [Builder.title] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun title(title: JsonField) = apply { this.title = title } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) + /** + * Returns an immutable instance of [EmploymentWithoutId]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): EmploymentWithoutId = + EmploymentWithoutId( + classCode, + (customFields ?: JsonMissing.of()).map { it.toImmutable() }, + department, + employment, + employmentStatus, + endDate, + firstName, + income, + (incomeHistory ?: JsonMissing.of()).map { it.toImmutable() }, + isActive, + lastName, + latestRehireDate, + location, + manager, + middleName, + sourceId, + startDate, + title, + additionalProperties.toMutableMap(), + ) } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + private var validated: Boolean = false - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun validate(): EmploymentWithoutId = apply { + if (validated) { + return@apply } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + classCode() + customFields().ifPresent { it.forEach { it.validate() } } + department().ifPresent { it.validate() } + employment().ifPresent { it.validate() } + employmentStatus().ifPresent { it.validate() } + endDate() + firstName() + income().ifPresent { it.validate() } + incomeHistory().ifPresent { it.forEach { it?.validate() } } + isActive() + lastName() + latestRehireDate() + location().ifPresent { it.validate() } + manager().ifPresent { it.validate() } + middleName() + sourceId() + startDate() + title() + validated = true } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) - } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (classCode.asKnown().isPresent) 1 else 0) + + (customFields.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (department.asKnown().getOrNull()?.validity() ?: 0) + + (employment.asKnown().getOrNull()?.validity() ?: 0) + + (employmentStatus.asKnown().getOrNull()?.validity() ?: 0) + + (if (endDate.asKnown().isPresent) 1 else 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (income.asKnown().getOrNull()?.validity() ?: 0) + + (incomeHistory.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } + ?: 0) + + (if (isActive.asKnown().isPresent) 1 else 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (if (latestRehireDate.asKnown().isPresent) 1 else 0) + + (location.asKnown().getOrNull()?.validity() ?: 0) + + (manager.asKnown().getOrNull()?.validity() ?: 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + + (if (sourceId.asKnown().isPresent) 1 else 0) + + (if (startDate.asKnown().isPresent) 1 else 0) + + (if (title.asKnown().isPresent) 1 else 0) - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + return /* spotless:off */ other is EmploymentWithoutId && classCode == other.classCode && customFields == other.customFields && department == other.department && employment == other.employment && employmentStatus == other.employmentStatus && endDate == other.endDate && firstName == other.firstName && income == other.income && incomeHistory == other.incomeHistory && isActive == other.isActive && lastName == other.lastName && latestRehireDate == other.latestRehireDate && location == other.location && manager == other.manager && middleName == other.middleName && sourceId == other.sourceId && startDate == other.startDate && title == other.title && additionalProperties == other.additionalProperties /* spotless:on */ } - fun build(): SandboxEmploymentUpdateParams = - SandboxEmploymentUpdateParams( - checkRequired("individualId", individualId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(classCode, customFields, department, employment, employmentStatus, endDate, firstName, income, incomeHistory, isActive, lastName, latestRehireDate, location, manager, middleName, sourceId, startDate, title, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "EmploymentWithoutId{classCode=$classCode, customFields=$customFields, department=$department, employment=$employment, employmentStatus=$employmentStatus, endDate=$endDate, firstName=$firstName, income=$income, incomeHistory=$incomeHistory, isActive=$isActive, lastName=$lastName, latestRehireDate=$latestRehireDate, location=$location, manager=$manager, middleName=$middleName, sourceId=$sourceId, startDate=$startDate, title=$title, additionalProperties=$additionalProperties}" } - @NoAutoDetect class CustomField - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("value") @ExcludeMissing private val value: JsonValue = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val value: JsonValue, + private val additionalProperties: MutableMap, ) { - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("value") @ExcludeMissing value: JsonValue = JsonMissing.of(), + ) : this(name, value, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") @JsonProperty("value") @ExcludeMissing fun _value(): JsonValue = value + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): CustomField = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [CustomField]. */ @JvmStatic fun builder() = Builder() } @@ -1127,8 +1761,16 @@ private constructor( fun name(name: String?) = name(JsonField.ofNullable(name)) - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } fun value(value: JsonValue) = apply { this.value = value } @@ -1152,9 +1794,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): CustomField = CustomField(name, value, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [CustomField]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CustomField = CustomField(name, value, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): CustomField = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1174,42 +1848,47 @@ private constructor( } /** The department object. */ - @NoAutoDetect class Department - @JsonCreator private constructor( - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val name: JsonField, + private val additionalProperties: MutableMap, ) { - /** The name of the department associated with the individual. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + @JsonCreator + private constructor( + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of() + ) : this(name, mutableMapOf()) - /** The name of the department associated with the individual. */ + /** + * The name of the department associated with the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Department = apply { - if (validated) { - return@apply - } - - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Department]. */ @JvmStatic fun builder() = Builder() } @@ -1228,10 +1907,16 @@ private constructor( /** The name of the department associated with the individual. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The name of the department associated with the individual. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The name of the department associated with the individual. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = apply { @@ -1253,9 +1938,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Department = Department(name, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Department]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Department = Department(name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Department = apply { + if (validated) { + return@apply + } + + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1275,56 +1992,65 @@ private constructor( } /** The employment object. */ - @NoAutoDetect class Employment - @JsonCreator private constructor( - @JsonProperty("subtype") - @ExcludeMissing - private val subtype: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val subtype: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("subtype") @ExcludeMissing subtype: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(subtype, type, mutableMapOf()) + /** * The secondary employment type of the individual. Options: `full_time`, `part_time`, * `intern`, `temp`, `seasonal` and `individual_contractor`. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun subtype(): Optional = Optional.ofNullable(subtype.getNullable("subtype")) + fun subtype(): Optional = subtype.getOptional("subtype") - /** The main employment type of the individual. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The main employment type of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") /** - * The secondary employment type of the individual. Options: `full_time`, `part_time`, - * `intern`, `temp`, `seasonal` and `individual_contractor`. + * Returns the raw JSON value of [subtype]. + * + * Unlike [subtype], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("subtype") @ExcludeMissing fun _subtype(): JsonField = subtype - /** The main employment type of the individual. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Employment = apply { - if (validated) { - return@apply - } - - subtype() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Employment]. */ @JvmStatic fun builder() = Builder() } @@ -1348,25 +2074,31 @@ private constructor( */ fun subtype(subtype: Subtype?) = subtype(JsonField.ofNullable(subtype)) - /** - * The secondary employment type of the individual. Options: `full_time`, `part_time`, - * `intern`, `temp`, `seasonal` and `individual_contractor`. - */ - fun subtype(subtype: Optional) = subtype(subtype.orElse(null)) + /** Alias for calling [Builder.subtype] with `subtype.orElse(null)`. */ + fun subtype(subtype: Optional) = subtype(subtype.getOrNull()) /** - * The secondary employment type of the individual. Options: `full_time`, `part_time`, - * `intern`, `temp`, `seasonal` and `individual_contractor`. + * Sets [Builder.subtype] to an arbitrary JSON value. + * + * You should usually call [Builder.subtype] with a well-typed [Subtype] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun subtype(subtype: JsonField) = apply { this.subtype = subtype } /** The main employment type of the individual. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** The main employment type of the individual. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** The main employment type of the individual. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -1388,9 +2120,45 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Employment = Employment(subtype, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Employment]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Employment = Employment(subtype, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Employment = apply { + if (validated) { + return@apply + } + + subtype().ifPresent { it.validate() } + type().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (subtype.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + /** * The secondary employment type of the individual. Options: `full_time`, `part_time`, * `intern`, `temp`, `seasonal` and `individual_contractor`. @@ -1509,6 +2277,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Subtype = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1610,6 +2405,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1760,6 +2582,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EmploymentStatus = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1774,40 +2623,47 @@ private constructor( } /** The manager object representing the manager of the individual within the org. */ - @NoAutoDetect class Manager - @JsonCreator private constructor( - @JsonProperty("id") @ExcludeMissing private val id: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val id: JsonField, + private val additionalProperties: MutableMap, ) { - /** A stable Finch `id` (UUID v4) for an individual in the company. */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of() + ) : this(id, mutableMapOf()) + + /** + * A stable Finch `id` (UUID v4) for an individual in the company. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Manager = apply { - if (validated) { - return@apply - } - - id() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Manager]. */ @JvmStatic fun builder() = Builder() } @@ -1826,7 +2682,13 @@ private constructor( /** A stable Finch `id` (UUID v4) for an individual in the company. */ fun id(id: String) = id(JsonField.of(id)) - /** A stable Finch `id` (UUID v4) for an individual in the company. */ + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun id(id: JsonField) = apply { this.id = id } fun additionalProperties(additionalProperties: Map) = apply { @@ -1848,9 +2710,41 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Manager = Manager(id, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Manager]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Manager = Manager(id, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Manager = apply { + if (validated) { + return@apply + } + + id() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (id.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxIndividualUpdateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxIndividualUpdateParams.kt index 8a1deb50..8349ea86 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxIndividualUpdateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxIndividualUpdateParams.kt @@ -11,16 +11,17 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Update sandbox individual */ class SandboxIndividualUpdateParams @@ -33,83 +34,179 @@ private constructor( fun individualId(): String = individualId + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun dob(): Optional = body.dob() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun emails(): Optional> = body.emails() /** * Social Security Number of the individual in **encrypted** format. This field is only * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set in * the body. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ fun encryptedSsn(): Optional = body.encryptedSsn() - /** The EEOC-defined ethnicity of the individual. */ + /** + * The EEOC-defined ethnicity of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun ethnicity(): Optional = body.ethnicity() - /** The legal first name of the individual. */ + /** + * The legal first name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun firstName(): Optional = body.firstName() - /** The gender of the individual. */ + /** + * The gender of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun gender(): Optional = body.gender() - /** The legal last name of the individual. */ + /** + * The legal last name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun lastName(): Optional = body.lastName() - /** The legal middle name of the individual. */ + /** + * The legal middle name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun middleName(): Optional = body.middleName() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun phoneNumbers(): Optional> = body.phoneNumbers() - /** The preferred name of the individual. */ + /** + * The preferred name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun preferredName(): Optional = body.preferredName() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun residence(): Optional = body.residence() /** * Social Security Number of the individual. This field is only available with the `ssn` scope * enabled and the `options: { include: ['ssn'] }` param set in the body. * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ fun ssn(): Optional = body.ssn() + /** + * Returns the raw JSON value of [dob]. + * + * Unlike [dob], this method doesn't throw if the JSON field has an unexpected type. + */ fun _dob(): JsonField = body._dob() + /** + * Returns the raw JSON value of [emails]. + * + * Unlike [emails], this method doesn't throw if the JSON field has an unexpected type. + */ fun _emails(): JsonField> = body._emails() /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set in - * the body. + * Returns the raw JSON value of [encryptedSsn]. + * + * Unlike [encryptedSsn], this method doesn't throw if the JSON field has an unexpected type. */ fun _encryptedSsn(): JsonField = body._encryptedSsn() - /** The EEOC-defined ethnicity of the individual. */ + /** + * Returns the raw JSON value of [ethnicity]. + * + * Unlike [ethnicity], this method doesn't throw if the JSON field has an unexpected type. + */ fun _ethnicity(): JsonField = body._ethnicity() - /** The legal first name of the individual. */ + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an unexpected type. + */ fun _firstName(): JsonField = body._firstName() - /** The gender of the individual. */ + /** + * Returns the raw JSON value of [gender]. + * + * Unlike [gender], this method doesn't throw if the JSON field has an unexpected type. + */ fun _gender(): JsonField = body._gender() - /** The legal last name of the individual. */ + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an unexpected type. + */ fun _lastName(): JsonField = body._lastName() - /** The legal middle name of the individual. */ + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an unexpected type. + */ fun _middleName(): JsonField = body._middleName() + /** + * Returns the raw JSON value of [phoneNumbers]. + * + * Unlike [phoneNumbers], this method doesn't throw if the JSON field has an unexpected type. + */ fun _phoneNumbers(): JsonField> = body._phoneNumbers() - /** The preferred name of the individual. */ + /** + * Returns the raw JSON value of [preferredName]. + * + * Unlike [preferredName], this method doesn't throw if the JSON field has an unexpected type. + */ fun _preferredName(): JsonField = body._preferredName() + /** + * Returns the raw JSON value of [residence]. + * + * Unlike [residence], this method doesn't throw if the JSON field has an unexpected type. + */ fun _residence(): JsonField = body._residence() /** - * Social Security Number of the individual. This field is only available with the `ssn` scope - * enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). + * Returns the raw JSON value of [ssn]. + * + * Unlike [ssn], this method doesn't throw if the JSON field has an unexpected type. */ fun _ssn(): JsonField = body._ssn() @@ -119,763 +216,1101 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): IndividualWithoutId = body + fun toBuilder() = Builder().from(this) - override fun _headers(): Headers = additionalHeaders + companion object { - override fun _queryParams(): QueryParams = additionalQueryParams + /** + * Returns a mutable builder for constructing an instance of + * [SandboxIndividualUpdateParams]. + * + * The following fields are required: + * ```java + * .individualId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - fun getPathParam(index: Int): String { - return when (index) { - 0 -> individualId - else -> "" + /** A builder for [SandboxIndividualUpdateParams]. */ + class Builder internal constructor() { + + private var individualId: String? = null + private var body: IndividualWithoutId.Builder = IndividualWithoutId.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(sandboxIndividualUpdateParams: SandboxIndividualUpdateParams) = apply { + individualId = sandboxIndividualUpdateParams.individualId + body = sandboxIndividualUpdateParams.body.toBuilder() + additionalHeaders = sandboxIndividualUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = sandboxIndividualUpdateParams.additionalQueryParams.toBuilder() } - } - @NoAutoDetect - class IndividualWithoutId - @JsonCreator - private constructor( - @JsonProperty("dob") @ExcludeMissing private val dob: JsonField = JsonMissing.of(), - @JsonProperty("emails") - @ExcludeMissing - private val emails: JsonField> = JsonMissing.of(), - @JsonProperty("encrypted_ssn") - @ExcludeMissing - private val encryptedSsn: JsonField = JsonMissing.of(), - @JsonProperty("ethnicity") - @ExcludeMissing - private val ethnicity: JsonField = JsonMissing.of(), - @JsonProperty("first_name") - @ExcludeMissing - private val firstName: JsonField = JsonMissing.of(), - @JsonProperty("gender") - @ExcludeMissing - private val gender: JsonField = JsonMissing.of(), - @JsonProperty("last_name") - @ExcludeMissing - private val lastName: JsonField = JsonMissing.of(), - @JsonProperty("middle_name") - @ExcludeMissing - private val middleName: JsonField = JsonMissing.of(), - @JsonProperty("phone_numbers") - @ExcludeMissing - private val phoneNumbers: JsonField> = JsonMissing.of(), - @JsonProperty("preferred_name") - @ExcludeMissing - private val preferredName: JsonField = JsonMissing.of(), - @JsonProperty("residence") - @ExcludeMissing - private val residence: JsonField = JsonMissing.of(), - @JsonProperty("ssn") @ExcludeMissing private val ssn: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + fun individualId(individualId: String) = apply { this.individualId = individualId } - fun dob(): Optional = Optional.ofNullable(dob.getNullable("dob")) + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [dob] + * - [emails] + * - [encryptedSsn] + * - [ethnicity] + * - [firstName] + * - etc. + */ + fun body(body: IndividualWithoutId) = apply { this.body = body.toBuilder() } + + fun dob(dob: String?) = apply { body.dob(dob) } + + /** Alias for calling [Builder.dob] with `dob.orElse(null)`. */ + fun dob(dob: Optional) = dob(dob.getOrNull()) + + /** + * Sets [Builder.dob] to an arbitrary JSON value. + * + * You should usually call [Builder.dob] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun dob(dob: JsonField) = apply { body.dob(dob) } + + fun emails(emails: List?) = apply { body.emails(emails) } + + /** Alias for calling [Builder.emails] with `emails.orElse(null)`. */ + fun emails(emails: Optional>) = emails(emails.getOrNull()) + + /** + * Sets [Builder.emails] to an arbitrary JSON value. + * + * You should usually call [Builder.emails] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun emails(emails: JsonField>) = apply { body.emails(emails) } - fun emails(): Optional> = Optional.ofNullable(emails.getNullable("emails")) + /** + * Adds a single [Email] to [emails]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEmail(email: Email) = apply { body.addEmail(email) } /** * Social Security Number of the individual in **encrypted** format. This field is only * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set * in the body. */ - fun encryptedSsn(): Optional = - Optional.ofNullable(encryptedSsn.getNullable("encrypted_ssn")) + fun encryptedSsn(encryptedSsn: String?) = apply { body.encryptedSsn(encryptedSsn) } + + /** Alias for calling [Builder.encryptedSsn] with `encryptedSsn.orElse(null)`. */ + fun encryptedSsn(encryptedSsn: Optional) = encryptedSsn(encryptedSsn.getOrNull()) + + /** + * Sets [Builder.encryptedSsn] to an arbitrary JSON value. + * + * You should usually call [Builder.encryptedSsn] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun encryptedSsn(encryptedSsn: JsonField) = apply { + body.encryptedSsn(encryptedSsn) + } /** The EEOC-defined ethnicity of the individual. */ - fun ethnicity(): Optional = - Optional.ofNullable(ethnicity.getNullable("ethnicity")) + fun ethnicity(ethnicity: Ethnicity?) = apply { body.ethnicity(ethnicity) } + + /** Alias for calling [Builder.ethnicity] with `ethnicity.orElse(null)`. */ + fun ethnicity(ethnicity: Optional) = ethnicity(ethnicity.getOrNull()) + + /** + * Sets [Builder.ethnicity] to an arbitrary JSON value. + * + * You should usually call [Builder.ethnicity] with a well-typed [Ethnicity] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun ethnicity(ethnicity: JsonField) = apply { body.ethnicity(ethnicity) } /** The legal first name of the individual. */ - fun firstName(): Optional = Optional.ofNullable(firstName.getNullable("first_name")) + fun firstName(firstName: String?) = apply { body.firstName(firstName) } + + /** Alias for calling [Builder.firstName] with `firstName.orElse(null)`. */ + fun firstName(firstName: Optional) = firstName(firstName.getOrNull()) + + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun firstName(firstName: JsonField) = apply { body.firstName(firstName) } /** The gender of the individual. */ - fun gender(): Optional = Optional.ofNullable(gender.getNullable("gender")) + fun gender(gender: Gender?) = apply { body.gender(gender) } + + /** Alias for calling [Builder.gender] with `gender.orElse(null)`. */ + fun gender(gender: Optional) = gender(gender.getOrNull()) + + /** + * Sets [Builder.gender] to an arbitrary JSON value. + * + * You should usually call [Builder.gender] with a well-typed [Gender] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun gender(gender: JsonField) = apply { body.gender(gender) } /** The legal last name of the individual. */ - fun lastName(): Optional = Optional.ofNullable(lastName.getNullable("last_name")) + fun lastName(lastName: String?) = apply { body.lastName(lastName) } - /** The legal middle name of the individual. */ - fun middleName(): Optional = - Optional.ofNullable(middleName.getNullable("middle_name")) + /** Alias for calling [Builder.lastName] with `lastName.orElse(null)`. */ + fun lastName(lastName: Optional) = lastName(lastName.getOrNull()) - fun phoneNumbers(): Optional> = - Optional.ofNullable(phoneNumbers.getNullable("phone_numbers")) + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun lastName(lastName: JsonField) = apply { body.lastName(lastName) } - /** The preferred name of the individual. */ - fun preferredName(): Optional = - Optional.ofNullable(preferredName.getNullable("preferred_name")) + /** The legal middle name of the individual. */ + fun middleName(middleName: String?) = apply { body.middleName(middleName) } - fun residence(): Optional = - Optional.ofNullable(residence.getNullable("residence")) + /** Alias for calling [Builder.middleName] with `middleName.orElse(null)`. */ + fun middleName(middleName: Optional) = middleName(middleName.getOrNull()) /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. */ - fun ssn(): Optional = Optional.ofNullable(ssn.getNullable("ssn")) + fun middleName(middleName: JsonField) = apply { body.middleName(middleName) } - @JsonProperty("dob") @ExcludeMissing fun _dob(): JsonField = dob + fun phoneNumbers(phoneNumbers: List?) = apply { + body.phoneNumbers(phoneNumbers) + } - @JsonProperty("emails") @ExcludeMissing fun _emails(): JsonField> = emails + /** Alias for calling [Builder.phoneNumbers] with `phoneNumbers.orElse(null)`. */ + fun phoneNumbers(phoneNumbers: Optional>) = + phoneNumbers(phoneNumbers.getOrNull()) /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set - * in the body. + * Sets [Builder.phoneNumbers] to an arbitrary JSON value. + * + * You should usually call [Builder.phoneNumbers] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. */ - @JsonProperty("encrypted_ssn") - @ExcludeMissing - fun _encryptedSsn(): JsonField = encryptedSsn - - /** The EEOC-defined ethnicity of the individual. */ - @JsonProperty("ethnicity") - @ExcludeMissing - fun _ethnicity(): JsonField = ethnicity + fun phoneNumbers(phoneNumbers: JsonField>) = apply { + body.phoneNumbers(phoneNumbers) + } - /** The legal first name of the individual. */ - @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName + /** + * Adds a single [PhoneNumber] to [phoneNumbers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addPhoneNumber(phoneNumber: PhoneNumber) = apply { body.addPhoneNumber(phoneNumber) } - /** The gender of the individual. */ - @JsonProperty("gender") @ExcludeMissing fun _gender(): JsonField = gender + /** The preferred name of the individual. */ + fun preferredName(preferredName: String?) = apply { body.preferredName(preferredName) } - /** The legal last name of the individual. */ - @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName + /** Alias for calling [Builder.preferredName] with `preferredName.orElse(null)`. */ + fun preferredName(preferredName: Optional) = + preferredName(preferredName.getOrNull()) - /** The legal middle name of the individual. */ - @JsonProperty("middle_name") - @ExcludeMissing - fun _middleName(): JsonField = middleName + /** + * Sets [Builder.preferredName] to an arbitrary JSON value. + * + * You should usually call [Builder.preferredName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun preferredName(preferredName: JsonField) = apply { + body.preferredName(preferredName) + } - @JsonProperty("phone_numbers") - @ExcludeMissing - fun _phoneNumbers(): JsonField> = phoneNumbers + fun residence(residence: Location?) = apply { body.residence(residence) } - /** The preferred name of the individual. */ - @JsonProperty("preferred_name") - @ExcludeMissing - fun _preferredName(): JsonField = preferredName + /** Alias for calling [Builder.residence] with `residence.orElse(null)`. */ + fun residence(residence: Optional) = residence(residence.getOrNull()) - @JsonProperty("residence") @ExcludeMissing fun _residence(): JsonField = residence + /** + * Sets [Builder.residence] to an arbitrary JSON value. + * + * You should usually call [Builder.residence] with a well-typed [Location] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun residence(residence: JsonField) = apply { body.residence(residence) } /** * Social Security Number of the individual. This field is only available with the `ssn` * scope enabled and the `options: { include: ['ssn'] }` param set in the body. * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). */ - @JsonProperty("ssn") @ExcludeMissing fun _ssn(): JsonField = ssn + fun ssn(ssn: String?) = apply { body.ssn(ssn) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** Alias for calling [Builder.ssn] with `ssn.orElse(null)`. */ + fun ssn(ssn: Optional) = ssn(ssn.getOrNull()) - private var validated: Boolean = false + /** + * Sets [Builder.ssn] to an arbitrary JSON value. + * + * You should usually call [Builder.ssn] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun ssn(ssn: JsonField) = apply { body.ssn(ssn) } - fun validate(): IndividualWithoutId = apply { - if (validated) { - return@apply - } + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - dob() - emails().ifPresent { it.forEach { it.validate() } } - encryptedSsn() - ethnicity() - firstName() - gender() - lastName() - middleName() - phoneNumbers().ifPresent { it.forEach { it?.validate() } } - preferredName() - residence().ifPresent { it.validate() } - ssn() - validated = true + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - fun toBuilder() = Builder().from(this) + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } - companion object { + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - @JvmStatic fun builder() = Builder() + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - /** A builder for [IndividualWithoutId]. */ - class Builder internal constructor() { - - private var dob: JsonField = JsonMissing.of() - private var emails: JsonField>? = null - private var encryptedSsn: JsonField = JsonMissing.of() - private var ethnicity: JsonField = JsonMissing.of() - private var firstName: JsonField = JsonMissing.of() - private var gender: JsonField = JsonMissing.of() - private var lastName: JsonField = JsonMissing.of() - private var middleName: JsonField = JsonMissing.of() - private var phoneNumbers: JsonField>? = null - private var preferredName: JsonField = JsonMissing.of() - private var residence: JsonField = JsonMissing.of() - private var ssn: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(individualWithoutId: IndividualWithoutId) = apply { - dob = individualWithoutId.dob - emails = individualWithoutId.emails.map { it.toMutableList() } - encryptedSsn = individualWithoutId.encryptedSsn - ethnicity = individualWithoutId.ethnicity - firstName = individualWithoutId.firstName - gender = individualWithoutId.gender - lastName = individualWithoutId.lastName - middleName = individualWithoutId.middleName - phoneNumbers = individualWithoutId.phoneNumbers.map { it.toMutableList() } - preferredName = individualWithoutId.preferredName - residence = individualWithoutId.residence - ssn = individualWithoutId.ssn - additionalProperties = individualWithoutId.additionalProperties.toMutableMap() - } - - fun dob(dob: String?) = dob(JsonField.ofNullable(dob)) - - fun dob(dob: Optional) = dob(dob.orElse(null)) - - fun dob(dob: JsonField) = apply { this.dob = dob } - - fun emails(emails: List?) = emails(JsonField.ofNullable(emails)) - - fun emails(emails: Optional>) = emails(emails.orElse(null)) - - fun emails(emails: JsonField>) = apply { - this.emails = emails.map { it.toMutableList() } - } - - fun addEmail(email: Email) = apply { - emails = - (emails ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(email) - } - } - - /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param - * set in the body. - */ - fun encryptedSsn(encryptedSsn: String?) = - encryptedSsn(JsonField.ofNullable(encryptedSsn)) - - /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param - * set in the body. - */ - fun encryptedSsn(encryptedSsn: Optional) = - encryptedSsn(encryptedSsn.orElse(null)) - - /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param - * set in the body. - */ - fun encryptedSsn(encryptedSsn: JsonField) = apply { - this.encryptedSsn = encryptedSsn - } - - /** The EEOC-defined ethnicity of the individual. */ - fun ethnicity(ethnicity: Ethnicity?) = ethnicity(JsonField.ofNullable(ethnicity)) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** The EEOC-defined ethnicity of the individual. */ - fun ethnicity(ethnicity: Optional) = ethnicity(ethnicity.orElse(null)) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** The EEOC-defined ethnicity of the individual. */ - fun ethnicity(ethnicity: JsonField) = apply { this.ethnicity = ethnicity } + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - /** The legal first name of the individual. */ - fun firstName(firstName: String?) = firstName(JsonField.ofNullable(firstName)) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - /** The legal first name of the individual. */ - fun firstName(firstName: Optional) = firstName(firstName.orElse(null)) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** The legal first name of the individual. */ - fun firstName(firstName: JsonField) = apply { this.firstName = firstName } + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** The gender of the individual. */ - fun gender(gender: Gender?) = gender(JsonField.ofNullable(gender)) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** The gender of the individual. */ - fun gender(gender: Optional) = gender(gender.orElse(null)) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** The gender of the individual. */ - fun gender(gender: JsonField) = apply { this.gender = gender } + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** The legal last name of the individual. */ - fun lastName(lastName: String?) = lastName(JsonField.ofNullable(lastName)) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** The legal last name of the individual. */ - fun lastName(lastName: Optional) = lastName(lastName.orElse(null)) + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - /** The legal last name of the individual. */ - fun lastName(lastName: JsonField) = apply { this.lastName = lastName } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - /** The legal middle name of the individual. */ - fun middleName(middleName: String?) = middleName(JsonField.ofNullable(middleName)) + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - /** The legal middle name of the individual. */ - fun middleName(middleName: Optional) = middleName(middleName.orElse(null)) + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - /** The legal middle name of the individual. */ - fun middleName(middleName: JsonField) = apply { this.middleName = middleName } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun phoneNumbers(phoneNumbers: List?) = - phoneNumbers(JsonField.ofNullable(phoneNumbers)) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - fun phoneNumbers(phoneNumbers: Optional>) = - phoneNumbers(phoneNumbers.orElse(null)) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - fun phoneNumbers(phoneNumbers: JsonField>) = apply { - this.phoneNumbers = phoneNumbers.map { it.toMutableList() } + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - fun addPhoneNumber(phoneNumber: PhoneNumber) = apply { - phoneNumbers = - (phoneNumbers ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(phoneNumber) - } - } + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } - /** The preferred name of the individual. */ - fun preferredName(preferredName: String?) = - preferredName(JsonField.ofNullable(preferredName)) + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - /** The preferred name of the individual. */ - fun preferredName(preferredName: Optional) = - preferredName(preferredName.orElse(null)) + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - /** The preferred name of the individual. */ - fun preferredName(preferredName: JsonField) = apply { - this.preferredName = preferredName + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - fun residence(residence: Location?) = residence(JsonField.ofNullable(residence)) - - fun residence(residence: Optional) = residence(residence.orElse(null)) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - fun residence(residence: JsonField) = apply { this.residence = residence } + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } - /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). - */ - fun ssn(ssn: String?) = ssn(JsonField.ofNullable(ssn)) + /** + * Returns an immutable instance of [SandboxIndividualUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .individualId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SandboxIndividualUpdateParams = + SandboxIndividualUpdateParams( + checkRequired("individualId", individualId), + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } - /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). - */ - fun ssn(ssn: Optional) = ssn(ssn.orElse(null)) + fun _body(): IndividualWithoutId = body - /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). - */ - fun ssn(ssn: JsonField) = apply { this.ssn = ssn } + fun _pathParam(index: Int): String = + when (index) { + 0 -> individualId + else -> "" + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } + override fun _headers(): Headers = additionalHeaders - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } + override fun _queryParams(): QueryParams = additionalQueryParams - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + class IndividualWithoutId + private constructor( + private val dob: JsonField, + private val emails: JsonField>, + private val encryptedSsn: JsonField, + private val ethnicity: JsonField, + private val firstName: JsonField, + private val gender: JsonField, + private val lastName: JsonField, + private val middleName: JsonField, + private val phoneNumbers: JsonField>, + private val preferredName: JsonField, + private val residence: JsonField, + private val ssn: JsonField, + private val additionalProperties: MutableMap, + ) { - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + @JsonCreator + private constructor( + @JsonProperty("dob") @ExcludeMissing dob: JsonField = JsonMissing.of(), + @JsonProperty("emails") + @ExcludeMissing + emails: JsonField> = JsonMissing.of(), + @JsonProperty("encrypted_ssn") + @ExcludeMissing + encryptedSsn: JsonField = JsonMissing.of(), + @JsonProperty("ethnicity") + @ExcludeMissing + ethnicity: JsonField = JsonMissing.of(), + @JsonProperty("first_name") + @ExcludeMissing + firstName: JsonField = JsonMissing.of(), + @JsonProperty("gender") @ExcludeMissing gender: JsonField = JsonMissing.of(), + @JsonProperty("last_name") + @ExcludeMissing + lastName: JsonField = JsonMissing.of(), + @JsonProperty("middle_name") + @ExcludeMissing + middleName: JsonField = JsonMissing.of(), + @JsonProperty("phone_numbers") + @ExcludeMissing + phoneNumbers: JsonField> = JsonMissing.of(), + @JsonProperty("preferred_name") + @ExcludeMissing + preferredName: JsonField = JsonMissing.of(), + @JsonProperty("residence") + @ExcludeMissing + residence: JsonField = JsonMissing.of(), + @JsonProperty("ssn") @ExcludeMissing ssn: JsonField = JsonMissing.of(), + ) : this( + dob, + emails, + encryptedSsn, + ethnicity, + firstName, + gender, + lastName, + middleName, + phoneNumbers, + preferredName, + residence, + ssn, + mutableMapOf(), + ) - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun dob(): Optional = dob.getOptional("dob") - fun build(): IndividualWithoutId = - IndividualWithoutId( - dob, - (emails ?: JsonMissing.of()).map { it.toImmutable() }, - encryptedSsn, - ethnicity, - firstName, - gender, - lastName, - middleName, - (phoneNumbers ?: JsonMissing.of()).map { it.toImmutable() }, - preferredName, - residence, - ssn, - additionalProperties.toImmutable(), - ) - } + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun emails(): Optional> = emails.getOptional("emails") - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** + * Social Security Number of the individual in **encrypted** format. This field is only + * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set + * in the body. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun encryptedSsn(): Optional = encryptedSsn.getOptional("encrypted_ssn") - return /* spotless:off */ other is IndividualWithoutId && dob == other.dob && emails == other.emails && encryptedSsn == other.encryptedSsn && ethnicity == other.ethnicity && firstName == other.firstName && gender == other.gender && lastName == other.lastName && middleName == other.middleName && phoneNumbers == other.phoneNumbers && preferredName == other.preferredName && residence == other.residence && ssn == other.ssn && additionalProperties == other.additionalProperties /* spotless:on */ - } + /** + * The EEOC-defined ethnicity of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun ethnicity(): Optional = ethnicity.getOptional("ethnicity") - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(dob, emails, encryptedSsn, ethnicity, firstName, gender, lastName, middleName, phoneNumbers, preferredName, residence, ssn, additionalProperties) } - /* spotless:on */ + /** + * The legal first name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun firstName(): Optional = firstName.getOptional("first_name") - override fun hashCode(): Int = hashCode + /** + * The gender of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun gender(): Optional = gender.getOptional("gender") - override fun toString() = - "IndividualWithoutId{dob=$dob, emails=$emails, encryptedSsn=$encryptedSsn, ethnicity=$ethnicity, firstName=$firstName, gender=$gender, lastName=$lastName, middleName=$middleName, phoneNumbers=$phoneNumbers, preferredName=$preferredName, residence=$residence, ssn=$ssn, additionalProperties=$additionalProperties}" - } + /** + * The legal last name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun lastName(): Optional = lastName.getOptional("last_name") - fun toBuilder() = Builder().from(this) + /** + * The legal middle name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun middleName(): Optional = middleName.getOptional("middle_name") - companion object { + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun phoneNumbers(): Optional> = phoneNumbers.getOptional("phone_numbers") - @JvmStatic fun builder() = Builder() - } + /** + * The preferred name of the individual. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun preferredName(): Optional = preferredName.getOptional("preferred_name") - /** A builder for [SandboxIndividualUpdateParams]. */ - @NoAutoDetect - class Builder internal constructor() { + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun residence(): Optional = residence.getOptional("residence") - private var individualId: String? = null - private var body: IndividualWithoutId.Builder = IndividualWithoutId.builder() - private var additionalHeaders: Headers.Builder = Headers.builder() - private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + /** + * Social Security Number of the individual. This field is only available with the `ssn` + * scope enabled and the `options: { include: ['ssn'] }` param set in the body. + * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun ssn(): Optional = ssn.getOptional("ssn") - @JvmSynthetic - internal fun from(sandboxIndividualUpdateParams: SandboxIndividualUpdateParams) = apply { - individualId = sandboxIndividualUpdateParams.individualId - body = sandboxIndividualUpdateParams.body.toBuilder() - additionalHeaders = sandboxIndividualUpdateParams.additionalHeaders.toBuilder() - additionalQueryParams = sandboxIndividualUpdateParams.additionalQueryParams.toBuilder() - } + /** + * Returns the raw JSON value of [dob]. + * + * Unlike [dob], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("dob") @ExcludeMissing fun _dob(): JsonField = dob - fun individualId(individualId: String) = apply { this.individualId = individualId } + /** + * Returns the raw JSON value of [emails]. + * + * Unlike [emails], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("emails") @ExcludeMissing fun _emails(): JsonField> = emails - fun dob(dob: String?) = apply { body.dob(dob) } + /** + * Returns the raw JSON value of [encryptedSsn]. + * + * Unlike [encryptedSsn], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("encrypted_ssn") + @ExcludeMissing + fun _encryptedSsn(): JsonField = encryptedSsn - fun dob(dob: Optional) = dob(dob.orElse(null)) + /** + * Returns the raw JSON value of [ethnicity]. + * + * Unlike [ethnicity], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("ethnicity") + @ExcludeMissing + fun _ethnicity(): JsonField = ethnicity - fun dob(dob: JsonField) = apply { body.dob(dob) } + /** + * Returns the raw JSON value of [firstName]. + * + * Unlike [firstName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("first_name") @ExcludeMissing fun _firstName(): JsonField = firstName - fun emails(emails: List?) = apply { body.emails(emails) } + /** + * Returns the raw JSON value of [gender]. + * + * Unlike [gender], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("gender") @ExcludeMissing fun _gender(): JsonField = gender - fun emails(emails: Optional>) = emails(emails.orElse(null)) + /** + * Returns the raw JSON value of [lastName]. + * + * Unlike [lastName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("last_name") @ExcludeMissing fun _lastName(): JsonField = lastName - fun emails(emails: JsonField>) = apply { body.emails(emails) } + /** + * Returns the raw JSON value of [middleName]. + * + * Unlike [middleName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("middle_name") + @ExcludeMissing + fun _middleName(): JsonField = middleName - fun addEmail(email: Email) = apply { body.addEmail(email) } + /** + * Returns the raw JSON value of [phoneNumbers]. + * + * Unlike [phoneNumbers], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("phone_numbers") + @ExcludeMissing + fun _phoneNumbers(): JsonField> = phoneNumbers /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set - * in the body. + * Returns the raw JSON value of [preferredName]. + * + * Unlike [preferredName], this method doesn't throw if the JSON field has an unexpected + * type. */ - fun encryptedSsn(encryptedSsn: String?) = apply { body.encryptedSsn(encryptedSsn) } + @JsonProperty("preferred_name") + @ExcludeMissing + fun _preferredName(): JsonField = preferredName /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set - * in the body. + * Returns the raw JSON value of [residence]. + * + * Unlike [residence], this method doesn't throw if the JSON field has an unexpected type. */ - fun encryptedSsn(encryptedSsn: Optional) = encryptedSsn(encryptedSsn.orElse(null)) + @JsonProperty("residence") @ExcludeMissing fun _residence(): JsonField = residence /** - * Social Security Number of the individual in **encrypted** format. This field is only - * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param set - * in the body. + * Returns the raw JSON value of [ssn]. + * + * Unlike [ssn], this method doesn't throw if the JSON field has an unexpected type. */ - fun encryptedSsn(encryptedSsn: JsonField) = apply { - body.encryptedSsn(encryptedSsn) - } + @JsonProperty("ssn") @ExcludeMissing fun _ssn(): JsonField = ssn - /** The EEOC-defined ethnicity of the individual. */ - fun ethnicity(ethnicity: Ethnicity?) = apply { body.ethnicity(ethnicity) } + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } - /** The EEOC-defined ethnicity of the individual. */ - fun ethnicity(ethnicity: Optional) = ethnicity(ethnicity.orElse(null)) + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - /** The EEOC-defined ethnicity of the individual. */ - fun ethnicity(ethnicity: JsonField) = apply { body.ethnicity(ethnicity) } + fun toBuilder() = Builder().from(this) - /** The legal first name of the individual. */ - fun firstName(firstName: String?) = apply { body.firstName(firstName) } + companion object { - /** The legal first name of the individual. */ - fun firstName(firstName: Optional) = firstName(firstName.orElse(null)) + /** Returns a mutable builder for constructing an instance of [IndividualWithoutId]. */ + @JvmStatic fun builder() = Builder() + } - /** The legal first name of the individual. */ - fun firstName(firstName: JsonField) = apply { body.firstName(firstName) } + /** A builder for [IndividualWithoutId]. */ + class Builder internal constructor() { - /** The gender of the individual. */ - fun gender(gender: Gender?) = apply { body.gender(gender) } + private var dob: JsonField = JsonMissing.of() + private var emails: JsonField>? = null + private var encryptedSsn: JsonField = JsonMissing.of() + private var ethnicity: JsonField = JsonMissing.of() + private var firstName: JsonField = JsonMissing.of() + private var gender: JsonField = JsonMissing.of() + private var lastName: JsonField = JsonMissing.of() + private var middleName: JsonField = JsonMissing.of() + private var phoneNumbers: JsonField>? = null + private var preferredName: JsonField = JsonMissing.of() + private var residence: JsonField = JsonMissing.of() + private var ssn: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() - /** The gender of the individual. */ - fun gender(gender: Optional) = gender(gender.orElse(null)) + @JvmSynthetic + internal fun from(individualWithoutId: IndividualWithoutId) = apply { + dob = individualWithoutId.dob + emails = individualWithoutId.emails.map { it.toMutableList() } + encryptedSsn = individualWithoutId.encryptedSsn + ethnicity = individualWithoutId.ethnicity + firstName = individualWithoutId.firstName + gender = individualWithoutId.gender + lastName = individualWithoutId.lastName + middleName = individualWithoutId.middleName + phoneNumbers = individualWithoutId.phoneNumbers.map { it.toMutableList() } + preferredName = individualWithoutId.preferredName + residence = individualWithoutId.residence + ssn = individualWithoutId.ssn + additionalProperties = individualWithoutId.additionalProperties.toMutableMap() + } - /** The gender of the individual. */ - fun gender(gender: JsonField) = apply { body.gender(gender) } + fun dob(dob: String?) = dob(JsonField.ofNullable(dob)) - /** The legal last name of the individual. */ - fun lastName(lastName: String?) = apply { body.lastName(lastName) } + /** Alias for calling [Builder.dob] with `dob.orElse(null)`. */ + fun dob(dob: Optional) = dob(dob.getOrNull()) - /** The legal last name of the individual. */ - fun lastName(lastName: Optional) = lastName(lastName.orElse(null)) + /** + * Sets [Builder.dob] to an arbitrary JSON value. + * + * You should usually call [Builder.dob] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun dob(dob: JsonField) = apply { this.dob = dob } - /** The legal last name of the individual. */ - fun lastName(lastName: JsonField) = apply { body.lastName(lastName) } + fun emails(emails: List?) = emails(JsonField.ofNullable(emails)) - /** The legal middle name of the individual. */ - fun middleName(middleName: String?) = apply { body.middleName(middleName) } + /** Alias for calling [Builder.emails] with `emails.orElse(null)`. */ + fun emails(emails: Optional>) = emails(emails.getOrNull()) - /** The legal middle name of the individual. */ - fun middleName(middleName: Optional) = middleName(middleName.orElse(null)) + /** + * Sets [Builder.emails] to an arbitrary JSON value. + * + * You should usually call [Builder.emails] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun emails(emails: JsonField>) = apply { + this.emails = emails.map { it.toMutableList() } + } - /** The legal middle name of the individual. */ - fun middleName(middleName: JsonField) = apply { body.middleName(middleName) } + /** + * Adds a single [Email] to [emails]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEmail(email: Email) = apply { + emails = + (emails ?: JsonField.of(mutableListOf())).also { + checkKnown("emails", it).add(email) + } + } - fun phoneNumbers(phoneNumbers: List?) = apply { - body.phoneNumbers(phoneNumbers) - } + /** + * Social Security Number of the individual in **encrypted** format. This field is only + * available with the `ssn` scope enabled and the `options: { include: ['ssn'] }` param + * set in the body. + */ + fun encryptedSsn(encryptedSsn: String?) = + encryptedSsn(JsonField.ofNullable(encryptedSsn)) - fun phoneNumbers(phoneNumbers: Optional>) = - phoneNumbers(phoneNumbers.orElse(null)) + /** Alias for calling [Builder.encryptedSsn] with `encryptedSsn.orElse(null)`. */ + fun encryptedSsn(encryptedSsn: Optional) = + encryptedSsn(encryptedSsn.getOrNull()) - fun phoneNumbers(phoneNumbers: JsonField>) = apply { - body.phoneNumbers(phoneNumbers) - } + /** + * Sets [Builder.encryptedSsn] to an arbitrary JSON value. + * + * You should usually call [Builder.encryptedSsn] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun encryptedSsn(encryptedSsn: JsonField) = apply { + this.encryptedSsn = encryptedSsn + } - fun addPhoneNumber(phoneNumber: PhoneNumber) = apply { body.addPhoneNumber(phoneNumber) } + /** The EEOC-defined ethnicity of the individual. */ + fun ethnicity(ethnicity: Ethnicity?) = ethnicity(JsonField.ofNullable(ethnicity)) - /** The preferred name of the individual. */ - fun preferredName(preferredName: String?) = apply { body.preferredName(preferredName) } + /** Alias for calling [Builder.ethnicity] with `ethnicity.orElse(null)`. */ + fun ethnicity(ethnicity: Optional) = ethnicity(ethnicity.getOrNull()) - /** The preferred name of the individual. */ - fun preferredName(preferredName: Optional) = - preferredName(preferredName.orElse(null)) + /** + * Sets [Builder.ethnicity] to an arbitrary JSON value. + * + * You should usually call [Builder.ethnicity] with a well-typed [Ethnicity] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun ethnicity(ethnicity: JsonField) = apply { this.ethnicity = ethnicity } - /** The preferred name of the individual. */ - fun preferredName(preferredName: JsonField) = apply { - body.preferredName(preferredName) - } + /** The legal first name of the individual. */ + fun firstName(firstName: String?) = firstName(JsonField.ofNullable(firstName)) - fun residence(residence: Location?) = apply { body.residence(residence) } + /** Alias for calling [Builder.firstName] with `firstName.orElse(null)`. */ + fun firstName(firstName: Optional) = firstName(firstName.getOrNull()) - fun residence(residence: Optional) = residence(residence.orElse(null)) + /** + * Sets [Builder.firstName] to an arbitrary JSON value. + * + * You should usually call [Builder.firstName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun firstName(firstName: JsonField) = apply { this.firstName = firstName } - fun residence(residence: JsonField) = apply { body.residence(residence) } + /** The gender of the individual. */ + fun gender(gender: Gender?) = gender(JsonField.ofNullable(gender)) - /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). - */ - fun ssn(ssn: String?) = apply { body.ssn(ssn) } + /** Alias for calling [Builder.gender] with `gender.orElse(null)`. */ + fun gender(gender: Optional) = gender(gender.getOrNull()) - /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). - */ - fun ssn(ssn: Optional) = ssn(ssn.orElse(null)) + /** + * Sets [Builder.gender] to an arbitrary JSON value. + * + * You should usually call [Builder.gender] with a well-typed [Gender] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun gender(gender: JsonField) = apply { this.gender = gender } - /** - * Social Security Number of the individual. This field is only available with the `ssn` - * scope enabled and the `options: { include: ['ssn'] }` param set in the body. - * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). - */ - fun ssn(ssn: JsonField) = apply { body.ssn(ssn) } + /** The legal last name of the individual. */ + fun lastName(lastName: String?) = lastName(JsonField.ofNullable(lastName)) - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - body.additionalProperties(additionalBodyProperties) - } + /** Alias for calling [Builder.lastName] with `lastName.orElse(null)`. */ + fun lastName(lastName: Optional) = lastName(lastName.getOrNull()) - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - body.putAdditionalProperty(key, value) - } + /** + * Sets [Builder.lastName] to an arbitrary JSON value. + * + * You should usually call [Builder.lastName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun lastName(lastName: JsonField) = apply { this.lastName = lastName } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - body.putAllAdditionalProperties(additionalBodyProperties) - } + /** The legal middle name of the individual. */ + fun middleName(middleName: String?) = middleName(JsonField.ofNullable(middleName)) - fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + /** Alias for calling [Builder.middleName] with `middleName.orElse(null)`. */ + fun middleName(middleName: Optional) = middleName(middleName.getOrNull()) - fun removeAllAdditionalBodyProperties(keys: Set) = apply { - body.removeAllAdditionalProperties(keys) - } + /** + * Sets [Builder.middleName] to an arbitrary JSON value. + * + * You should usually call [Builder.middleName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun middleName(middleName: JsonField) = apply { this.middleName = middleName } - fun additionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + fun phoneNumbers(phoneNumbers: List?) = + phoneNumbers(JsonField.ofNullable(phoneNumbers)) - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllAdditionalHeaders(additionalHeaders) - } + /** Alias for calling [Builder.phoneNumbers] with `phoneNumbers.orElse(null)`. */ + fun phoneNumbers(phoneNumbers: Optional>) = + phoneNumbers(phoneNumbers.getOrNull()) - fun putAdditionalHeader(name: String, value: String) = apply { - additionalHeaders.put(name, value) - } + /** + * Sets [Builder.phoneNumbers] to an arbitrary JSON value. + * + * You should usually call [Builder.phoneNumbers] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun phoneNumbers(phoneNumbers: JsonField>) = apply { + this.phoneNumbers = phoneNumbers.map { it.toMutableList() } + } - fun putAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.put(name, values) - } + /** + * Adds a single [PhoneNumber] to [phoneNumbers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addPhoneNumber(phoneNumber: PhoneNumber) = apply { + phoneNumbers = + (phoneNumbers ?: JsonField.of(mutableListOf())).also { + checkKnown("phoneNumbers", it).add(phoneNumber) + } + } - fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** The preferred name of the individual. */ + fun preferredName(preferredName: String?) = + preferredName(JsonField.ofNullable(preferredName)) - fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.putAll(additionalHeaders) - } + /** Alias for calling [Builder.preferredName] with `preferredName.orElse(null)`. */ + fun preferredName(preferredName: Optional) = + preferredName(preferredName.getOrNull()) - fun replaceAdditionalHeaders(name: String, value: String) = apply { - additionalHeaders.replace(name, value) - } + /** + * Sets [Builder.preferredName] to an arbitrary JSON value. + * + * You should usually call [Builder.preferredName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun preferredName(preferredName: JsonField) = apply { + this.preferredName = preferredName + } - fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { - additionalHeaders.replace(name, values) - } + fun residence(residence: Location?) = residence(JsonField.ofNullable(residence)) - fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** Alias for calling [Builder.residence] with `residence.orElse(null)`. */ + fun residence(residence: Optional) = residence(residence.getOrNull()) - fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.replaceAll(additionalHeaders) - } + /** + * Sets [Builder.residence] to an arbitrary JSON value. + * + * You should usually call [Builder.residence] with a well-typed [Location] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun residence(residence: JsonField) = apply { this.residence = residence } - fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + /** + * Social Security Number of the individual. This field is only available with the `ssn` + * scope enabled and the `options: { include: ['ssn'] }` param set in the body. + * [Click here to learn more about enabling the SSN field](/developer-resources/Enable-SSN-Field). + */ + fun ssn(ssn: String?) = ssn(JsonField.ofNullable(ssn)) - fun removeAllAdditionalHeaders(names: Set) = apply { - additionalHeaders.removeAll(names) - } + /** Alias for calling [Builder.ssn] with `ssn.orElse(null)`. */ + fun ssn(ssn: Optional) = ssn(ssn.getOrNull()) - fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + /** + * Sets [Builder.ssn] to an arbitrary JSON value. + * + * You should usually call [Builder.ssn] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun ssn(ssn: JsonField) = apply { this.ssn = ssn } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllAdditionalQueryParams(additionalQueryParams) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun putAdditionalQueryParam(key: String, value: String) = apply { - additionalQueryParams.put(key, value) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun putAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.put(key, values) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.putAll(additionalQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.putAll(additionalQueryParams) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - fun replaceAdditionalQueryParams(key: String, value: String) = apply { - additionalQueryParams.replace(key, value) + /** + * Returns an immutable instance of [IndividualWithoutId]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): IndividualWithoutId = + IndividualWithoutId( + dob, + (emails ?: JsonMissing.of()).map { it.toImmutable() }, + encryptedSsn, + ethnicity, + firstName, + gender, + lastName, + middleName, + (phoneNumbers ?: JsonMissing.of()).map { it.toImmutable() }, + preferredName, + residence, + ssn, + additionalProperties.toMutableMap(), + ) } - fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { - additionalQueryParams.replace(key, values) - } + private var validated: Boolean = false - fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun validate(): IndividualWithoutId = apply { + if (validated) { + return@apply + } + + dob() + emails().ifPresent { it.forEach { it.validate() } } + encryptedSsn() + ethnicity().ifPresent { it.validate() } + firstName() + gender().ifPresent { it.validate() } + lastName() + middleName() + phoneNumbers().ifPresent { it.forEach { it?.validate() } } + preferredName() + residence().ifPresent { it.validate() } + ssn() + validated = true } - fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = - apply { - this.additionalQueryParams.replaceAll(additionalQueryParams) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false } - fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (dob.asKnown().isPresent) 1 else 0) + + (emails.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (encryptedSsn.asKnown().isPresent) 1 else 0) + + (ethnicity.asKnown().getOrNull()?.validity() ?: 0) + + (if (firstName.asKnown().isPresent) 1 else 0) + + (gender.asKnown().getOrNull()?.validity() ?: 0) + + (if (lastName.asKnown().isPresent) 1 else 0) + + (if (middleName.asKnown().isPresent) 1 else 0) + + (phoneNumbers.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (preferredName.asKnown().isPresent) 1 else 0) + + (residence.asKnown().getOrNull()?.validity() ?: 0) + + (if (ssn.asKnown().isPresent) 1 else 0) - fun removeAllAdditionalQueryParams(keys: Set) = apply { - additionalQueryParams.removeAll(keys) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is IndividualWithoutId && dob == other.dob && emails == other.emails && encryptedSsn == other.encryptedSsn && ethnicity == other.ethnicity && firstName == other.firstName && gender == other.gender && lastName == other.lastName && middleName == other.middleName && phoneNumbers == other.phoneNumbers && preferredName == other.preferredName && residence == other.residence && ssn == other.ssn && additionalProperties == other.additionalProperties /* spotless:on */ } - fun build(): SandboxIndividualUpdateParams = - SandboxIndividualUpdateParams( - checkRequired("individualId", individualId), - body.build(), - additionalHeaders.build(), - additionalQueryParams.build(), - ) + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(dob, emails, encryptedSsn, ethnicity, firstName, gender, lastName, middleName, phoneNumbers, preferredName, residence, ssn, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "IndividualWithoutId{dob=$dob, emails=$emails, encryptedSsn=$encryptedSsn, ethnicity=$ethnicity, firstName=$firstName, gender=$gender, lastName=$lastName, middleName=$middleName, phoneNumbers=$phoneNumbers, preferredName=$preferredName, residence=$residence, ssn=$ssn, additionalProperties=$additionalProperties}" } - @NoAutoDetect class Email - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Email = apply { - if (validated) { - return@apply - } - - data() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Email]. */ @JvmStatic fun builder() = Builder() } @@ -895,12 +1330,27 @@ private constructor( fun data(data: String) = data(JsonField.of(data)) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun data(data: JsonField) = apply { this.data = data } fun type(type: Type?) = type(JsonField.ofNullable(type)) - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -922,9 +1372,44 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Email = Email(data, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Email]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Email = Email(data, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Email = apply { + if (validated) { + return@apply + } + + data() + type().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -1012,6 +1497,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1167,6 +1679,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Ethnicity = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1277,6 +1816,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Gender = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1290,46 +1856,60 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class PhoneNumber - @JsonCreator private constructor( - @JsonProperty("data") - @ExcludeMissing - private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(data, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PhoneNumber = apply { - if (validated) { - return@apply - } - - data() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [PhoneNumber]. */ @JvmStatic fun builder() = Builder() } @@ -1347,14 +1927,32 @@ private constructor( additionalProperties = phoneNumber.additionalProperties.toMutableMap() } - fun data(data: String) = data(JsonField.of(data)) + fun data(data: String?) = data(JsonField.ofNullable(data)) + + /** Alias for calling [Builder.data] with `data.orElse(null)`. */ + fun data(data: Optional) = data(data.getOrNull()) + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun data(data: JsonField) = apply { this.data = data } fun type(type: Type?) = type(JsonField.ofNullable(type)) - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -1376,9 +1974,44 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): PhoneNumber = PhoneNumber(data, type, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [PhoneNumber]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): PhoneNumber = PhoneNumber(data, type, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): PhoneNumber = apply { + if (validated) { + return@apply + } + + data() + type().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (data.asKnown().isPresent) 1 else 0) + (type.asKnown().getOrNull()?.validity() ?: 0) + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { /** @@ -1466,6 +2099,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobConfiguration.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobConfiguration.kt index 28c765c7..db95642a 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobConfiguration.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobConfiguration.kt @@ -11,54 +11,79 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class SandboxJobConfiguration -@JsonCreator private constructor( - @JsonProperty("completion_status") - @ExcludeMissing - private val completionStatus: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val completionStatus: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("completion_status") + @ExcludeMissing + completionStatus: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(completionStatus, type, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun completionStatus(): CompletionStatus = completionStatus.getRequired("completion_status") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun type(): Type = type.getRequired("type") + /** + * Returns the raw JSON value of [completionStatus]. + * + * Unlike [completionStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("completion_status") @ExcludeMissing fun _completionStatus(): JsonField = completionStatus + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SandboxJobConfiguration = apply { - if (validated) { - return@apply - } - - completionStatus() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [SandboxJobConfiguration]. + * + * The following fields are required: + * ```java + * .completionStatus() + * .type() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -79,12 +104,25 @@ private constructor( fun completionStatus(completionStatus: CompletionStatus) = completionStatus(JsonField.of(completionStatus)) + /** + * Sets [Builder.completionStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.completionStatus] with a well-typed [CompletionStatus] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun completionStatus(completionStatus: JsonField) = apply { this.completionStatus = completionStatus } fun type(type: Type) = type(JsonField.of(type)) + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -106,14 +144,57 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SandboxJobConfiguration]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .completionStatus() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): SandboxJobConfiguration = SandboxJobConfiguration( checkRequired("completionStatus", completionStatus), checkRequired("type", type), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): SandboxJobConfiguration = apply { + if (validated) { + return@apply + } + + completionStatus().validate() + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (completionStatus.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class CompletionStatus @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -214,6 +295,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): CompletionStatus = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -305,6 +413,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobConfigurationRetrieveParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobConfigurationRetrieveParams.kt index b13948c7..85e0f79d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobConfigurationRetrieveParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobConfigurationRetrieveParams.kt @@ -2,7 +2,6 @@ package com.tryfinch.api.models -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams @@ -19,21 +18,20 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): SandboxJobConfigurationRetrieveParams = builder().build() + /** + * Returns a mutable builder for constructing an instance of + * [SandboxJobConfigurationRetrieveParams]. + */ @JvmStatic fun builder() = Builder() } /** A builder for [SandboxJobConfigurationRetrieveParams]. */ - @NoAutoDetect class Builder internal constructor() { private var additionalHeaders: Headers.Builder = Headers.builder() @@ -146,6 +144,11 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [SandboxJobConfigurationRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SandboxJobConfigurationRetrieveParams = SandboxJobConfigurationRetrieveParams( additionalHeaders.build(), @@ -153,6 +156,10 @@ private constructor( ) } + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobConfigurationUpdateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobConfigurationUpdateParams.kt index 72a0a4d2..bd0c1ba4 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobConfigurationUpdateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobConfigurationUpdateParams.kt @@ -3,7 +3,6 @@ package com.tryfinch.api.models import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers @@ -27,21 +26,23 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): SandboxJobConfiguration = sandboxJobConfiguration - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SandboxJobConfigurationUpdateParams]. + * + * The following fields are required: + * ```java + * .sandboxJobConfiguration() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [SandboxJobConfigurationUpdateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var sandboxJobConfiguration: SandboxJobConfiguration? = null @@ -160,6 +161,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [SandboxJobConfigurationUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .sandboxJobConfiguration() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): SandboxJobConfigurationUpdateParams = SandboxJobConfigurationUpdateParams( checkRequired("sandboxJobConfiguration", sandboxJobConfiguration), @@ -168,6 +181,12 @@ private constructor( ) } + fun _body(): SandboxJobConfiguration = sandboxJobConfiguration + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobCreateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobCreateParams.kt index 089b6b57..c102b323 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobCreateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxJobCreateParams.kt @@ -11,15 +11,14 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params import com.tryfinch.api.core.checkRequired import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects +import kotlin.jvm.optionals.getOrNull /** Enqueue a new sandbox job */ class SandboxJobCreateParams @@ -29,10 +28,19 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { - /** The type of job to start. Currently the only supported type is `data_sync_all` */ + /** + * The type of job to start. Currently the only supported type is `data_sync_all` + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun type(): Type = body.type() - /** The type of job to start. Currently the only supported type is `data_sync_all` */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ fun _type(): JsonField = body._type() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -41,116 +49,22 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - /** The type of job to start. Currently the only supported type is `data_sync_all` */ - fun type(): Type = type.getRequired("type") - - /** The type of job to start. Currently the only supported type is `data_sync_all` */ - @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - type() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var type: JsonField? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - type = body.type - additionalProperties = body.additionalProperties.toMutableMap() - } - - /** The type of job to start. Currently the only supported type is `data_sync_all` */ - fun type(type: Type) = type(JsonField.of(type)) - - /** The type of job to start. Currently the only supported type is `data_sync_all` */ - fun type(type: JsonField) = apply { this.type = type } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = - Body(checkRequired("type", type), additionalProperties.toImmutable()) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = "Body{type=$type, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [SandboxJobCreateParams]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ @JvmStatic fun builder() = Builder() } /** A builder for [SandboxJobCreateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -164,10 +78,24 @@ private constructor( additionalQueryParams = sandboxJobCreateParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [type] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + /** The type of job to start. Currently the only supported type is `data_sync_all` */ fun type(type: Type) = apply { body.type(type) } - /** The type of job to start. Currently the only supported type is `data_sync_all` */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { body.type(type) } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { @@ -287,6 +215,18 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [SandboxJobCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): SandboxJobCreateParams = SandboxJobCreateParams( body.build(), @@ -295,6 +235,166 @@ private constructor( ) } + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + private constructor( + private val type: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of() + ) : this(type, mutableMapOf()) + + /** + * The type of job to start. Currently the only supported type is `data_sync_all` + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun type(): Type = type.getRequired("type") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + type = body.type + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The type of job to start. Currently the only supported type is `data_sync_all` */ + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body(checkRequired("type", type), additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + type().validate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (type.asKnown().getOrNull()?.validity() ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = "Body{type=$type, additionalProperties=$additionalProperties}" + } + /** The type of job to start. Currently the only supported type is `data_sync_all` */ class Type @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -374,6 +474,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxPaymentCreateParams.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxPaymentCreateParams.kt index 27e89a23..480911e5 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxPaymentCreateParams.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SandboxPaymentCreateParams.kt @@ -11,15 +11,16 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.Params +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.http.QueryParams -import com.tryfinch.api.core.immutableEmptyMap import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** Add a new sandbox payment */ class SandboxPaymentCreateParams @@ -29,16 +30,43 @@ private constructor( private val additionalQueryParams: QueryParams, ) : Params { + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun endDate(): Optional = body.endDate() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun payStatements(): Optional> = body.payStatements() + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun startDate(): Optional = body.startDate() + /** + * Returns the raw JSON value of [endDate]. + * + * Unlike [endDate], this method doesn't throw if the JSON field has an unexpected type. + */ fun _endDate(): JsonField = body._endDate() + /** + * Returns the raw JSON value of [payStatements]. + * + * Unlike [payStatements], this method doesn't throw if the JSON field has an unexpected type. + */ fun _payStatements(): JsonField> = body._payStatements() + /** + * Returns the raw JSON value of [startDate]. + * + * Unlike [startDate], this method doesn't throw if the JSON field has an unexpected type. + */ fun _startDate(): JsonField = body._startDate() fun _additionalBodyProperties(): Map = body._additionalProperties() @@ -47,173 +75,19 @@ private constructor( fun _additionalQueryParams(): QueryParams = additionalQueryParams - @JvmSynthetic internal fun _body(): Body = body - - override fun _headers(): Headers = additionalHeaders - - override fun _queryParams(): QueryParams = additionalQueryParams - - /** - * Fields to configure the payment. Takes all fields from the `/payment` endpoint. All fields - * are optional. - */ - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("end_date") - @ExcludeMissing - private val endDate: JsonField = JsonMissing.of(), - @JsonProperty("pay_statements") - @ExcludeMissing - private val payStatements: JsonField> = JsonMissing.of(), - @JsonProperty("start_date") - @ExcludeMissing - private val startDate: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { - - fun endDate(): Optional = Optional.ofNullable(endDate.getNullable("end_date")) - - fun payStatements(): Optional> = - Optional.ofNullable(payStatements.getNullable("pay_statements")) - - fun startDate(): Optional = Optional.ofNullable(startDate.getNullable("start_date")) - - @JsonProperty("end_date") @ExcludeMissing fun _endDate(): JsonField = endDate - - @JsonProperty("pay_statements") - @ExcludeMissing - fun _payStatements(): JsonField> = payStatements - - @JsonProperty("start_date") @ExcludeMissing fun _startDate(): JsonField = startDate - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - endDate() - payStatements().ifPresent { it.forEach { it.validate() } } - startDate() - validated = true - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - /** A builder for [Body]. */ - class Builder internal constructor() { - - private var endDate: JsonField = JsonMissing.of() - private var payStatements: JsonField>? = null - private var startDate: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(body: Body) = apply { - endDate = body.endDate - payStatements = body.payStatements.map { it.toMutableList() } - startDate = body.startDate - additionalProperties = body.additionalProperties.toMutableMap() - } - - fun endDate(endDate: String) = endDate(JsonField.of(endDate)) - - fun endDate(endDate: JsonField) = apply { this.endDate = endDate } - - fun payStatements(payStatements: List) = - payStatements(JsonField.of(payStatements)) - - fun payStatements(payStatements: JsonField>) = apply { - this.payStatements = payStatements.map { it.toMutableList() } - } - - fun addPayStatement(payStatement: PayStatement) = apply { - payStatements = - (payStatements ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(payStatement) - } - } - - fun startDate(startDate: String) = startDate(JsonField.of(startDate)) - - fun startDate(startDate: JsonField) = apply { this.startDate = startDate } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - putAllAdditionalProperties(additionalProperties) - } - - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - - fun removeAllAdditionalProperties(keys: Set) = apply { - keys.forEach(::removeAdditionalProperty) - } - - fun build(): Body = - Body( - endDate, - (payStatements ?: JsonMissing.of()).map { it.toImmutable() }, - startDate, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Body && endDate == other.endDate && payStatements == other.payStatements && startDate == other.startDate && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(endDate, payStatements, startDate, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Body{endDate=$endDate, payStatements=$payStatements, startDate=$startDate, additionalProperties=$additionalProperties}" - } - fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun none(): SandboxPaymentCreateParams = builder().build() + /** + * Returns a mutable builder for constructing an instance of [SandboxPaymentCreateParams]. + */ @JvmStatic fun builder() = Builder() } /** A builder for [SandboxPaymentCreateParams]. */ - @NoAutoDetect class Builder internal constructor() { private var body: Body.Builder = Body.builder() @@ -227,24 +101,60 @@ private constructor( additionalQueryParams = sandboxPaymentCreateParams.additionalQueryParams.toBuilder() } + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [endDate] + * - [payStatements] + * - [startDate] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + fun endDate(endDate: String) = apply { body.endDate(endDate) } + /** + * Sets [Builder.endDate] to an arbitrary JSON value. + * + * You should usually call [Builder.endDate] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun endDate(endDate: JsonField) = apply { body.endDate(endDate) } fun payStatements(payStatements: List) = apply { body.payStatements(payStatements) } + /** + * Sets [Builder.payStatements] to an arbitrary JSON value. + * + * You should usually call [Builder.payStatements] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun payStatements(payStatements: JsonField>) = apply { body.payStatements(payStatements) } + /** + * Adds a single [PayStatement] to [payStatements]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addPayStatement(payStatement: PayStatement) = apply { body.addPayStatement(payStatement) } fun startDate(startDate: String) = apply { body.startDate(startDate) } + /** + * Sets [Builder.startDate] to an arbitrary JSON value. + * + * You should usually call [Builder.startDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun startDate(startDate: JsonField) = apply { body.startDate(startDate) } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { @@ -364,6 +274,11 @@ private constructor( additionalQueryParams.removeAll(keys) } + /** + * Returns an immutable instance of [SandboxPaymentCreateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SandboxPaymentCreateParams = SandboxPaymentCreateParams( body.build(), @@ -372,143 +287,476 @@ private constructor( ) } - @NoAutoDetect - class PayStatement - @JsonCreator + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + /** + * Fields to configure the payment. Takes all fields from the `/payment` endpoint. All fields + * are optional. + */ + class Body private constructor( - @JsonProperty("earnings") - @ExcludeMissing - private val earnings: JsonField> = JsonMissing.of(), - @JsonProperty("employee_deductions") - @ExcludeMissing - private val employeeDeductions: JsonField> = JsonMissing.of(), - @JsonProperty("employer_contributions") - @ExcludeMissing - private val employerContributions: JsonField> = - JsonMissing.of(), - @JsonProperty("gross_pay") - @ExcludeMissing - private val grossPay: JsonField = JsonMissing.of(), - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonProperty("net_pay") - @ExcludeMissing - private val netPay: JsonField = JsonMissing.of(), - @JsonProperty("payment_method") - @ExcludeMissing - private val paymentMethod: JsonField = JsonMissing.of(), - @JsonProperty("taxes") - @ExcludeMissing - private val taxes: JsonField> = JsonMissing.of(), - @JsonProperty("total_hours") + private val endDate: JsonField, + private val payStatements: JsonField>, + private val startDate: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("end_date") @ExcludeMissing endDate: JsonField = JsonMissing.of(), + @JsonProperty("pay_statements") + @ExcludeMissing + payStatements: JsonField> = JsonMissing.of(), + @JsonProperty("start_date") + @ExcludeMissing + startDate: JsonField = JsonMissing.of(), + ) : this(endDate, payStatements, startDate, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun endDate(): Optional = endDate.getOptional("end_date") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun payStatements(): Optional> = + payStatements.getOptional("pay_statements") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun startDate(): Optional = startDate.getOptional("start_date") + + /** + * Returns the raw JSON value of [endDate]. + * + * Unlike [endDate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("end_date") @ExcludeMissing fun _endDate(): JsonField = endDate + + /** + * Returns the raw JSON value of [payStatements]. + * + * Unlike [payStatements], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("pay_statements") @ExcludeMissing - private val totalHours: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), + fun _payStatements(): JsonField> = payStatements + + /** + * Returns the raw JSON value of [startDate]. + * + * Unlike [startDate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("start_date") @ExcludeMissing fun _startDate(): JsonField = startDate + @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } - /** The array of earnings objects associated with this pay statement */ - fun earnings(): Optional> = - Optional.ofNullable(earnings.getNullable("earnings")) + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - /** The array of deductions objects associated with this pay statement. */ - fun employeeDeductions(): Optional> = - Optional.ofNullable(employeeDeductions.getNullable("employee_deductions")) + fun toBuilder() = Builder().from(this) - fun employerContributions(): Optional> = - Optional.ofNullable(employerContributions.getNullable("employer_contributions")) + companion object { - fun grossPay(): Optional = Optional.ofNullable(grossPay.getNullable("gross_pay")) + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() + } - /** A stable Finch `id` (UUID v4) for an individual in the company */ - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) + /** A builder for [Body]. */ + class Builder internal constructor() { - fun netPay(): Optional = Optional.ofNullable(netPay.getNullable("net_pay")) + private var endDate: JsonField = JsonMissing.of() + private var payStatements: JsonField>? = null + private var startDate: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() - /** The payment method. */ - fun paymentMethod(): Optional = - Optional.ofNullable(paymentMethod.getNullable("payment_method")) + @JvmSynthetic + internal fun from(body: Body) = apply { + endDate = body.endDate + payStatements = body.payStatements.map { it.toMutableList() } + startDate = body.startDate + additionalProperties = body.additionalProperties.toMutableMap() + } - /** The array of taxes objects associated with this pay statement. */ - fun taxes(): Optional> = Optional.ofNullable(taxes.getNullable("taxes")) + fun endDate(endDate: String) = endDate(JsonField.of(endDate)) - /** The number of hours worked for this pay period */ - fun totalHours(): Optional = - Optional.ofNullable(totalHours.getNullable("total_hours")) + /** + * Sets [Builder.endDate] to an arbitrary JSON value. + * + * You should usually call [Builder.endDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun endDate(endDate: JsonField) = apply { this.endDate = endDate } - /** The type of the payment associated with the pay statement. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + fun payStatements(payStatements: List) = + payStatements(JsonField.of(payStatements)) + + /** + * Sets [Builder.payStatements] to an arbitrary JSON value. + * + * You should usually call [Builder.payStatements] with a well-typed + * `List` value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun payStatements(payStatements: JsonField>) = apply { + this.payStatements = payStatements.map { it.toMutableList() } + } + + /** + * Adds a single [PayStatement] to [payStatements]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addPayStatement(payStatement: PayStatement) = apply { + payStatements = + (payStatements ?: JsonField.of(mutableListOf())).also { + checkKnown("payStatements", it).add(payStatement) + } + } - /** The array of earnings objects associated with this pay statement */ + fun startDate(startDate: String) = startDate(JsonField.of(startDate)) + + /** + * Sets [Builder.startDate] to an arbitrary JSON value. + * + * You should usually call [Builder.startDate] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun startDate(startDate: JsonField) = apply { this.startDate = startDate } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = + Body( + endDate, + (payStatements ?: JsonMissing.of()).map { it.toImmutable() }, + startDate, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + endDate() + payStatements().ifPresent { it.forEach { it.validate() } } + startDate() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (endDate.asKnown().isPresent) 1 else 0) + + (payStatements.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (startDate.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Body && endDate == other.endDate && payStatements == other.payStatements && startDate == other.startDate && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(endDate, payStatements, startDate, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{endDate=$endDate, payStatements=$payStatements, startDate=$startDate, additionalProperties=$additionalProperties}" + } + + class PayStatement + private constructor( + private val earnings: JsonField>, + private val employeeDeductions: JsonField>, + private val employerContributions: JsonField>, + private val grossPay: JsonField, + private val individualId: JsonField, + private val netPay: JsonField, + private val paymentMethod: JsonField, + private val taxes: JsonField>, + private val totalHours: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("earnings") + @ExcludeMissing + earnings: JsonField> = JsonMissing.of(), + @JsonProperty("employee_deductions") + @ExcludeMissing + employeeDeductions: JsonField> = JsonMissing.of(), + @JsonProperty("employer_contributions") + @ExcludeMissing + employerContributions: JsonField> = JsonMissing.of(), + @JsonProperty("gross_pay") + @ExcludeMissing + grossPay: JsonField = JsonMissing.of(), + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of(), + @JsonProperty("net_pay") @ExcludeMissing netPay: JsonField = JsonMissing.of(), + @JsonProperty("payment_method") + @ExcludeMissing + paymentMethod: JsonField = JsonMissing.of(), + @JsonProperty("taxes") @ExcludeMissing taxes: JsonField> = JsonMissing.of(), + @JsonProperty("total_hours") + @ExcludeMissing + totalHours: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this( + earnings, + employeeDeductions, + employerContributions, + grossPay, + individualId, + netPay, + paymentMethod, + taxes, + totalHours, + type, + mutableMapOf(), + ) + + /** + * The array of earnings objects associated with this pay statement + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun earnings(): Optional> = earnings.getOptional("earnings") + + /** + * The array of deductions objects associated with this pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun employeeDeductions(): Optional> = + employeeDeductions.getOptional("employee_deductions") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun employerContributions(): Optional> = + employerContributions.getOptional("employer_contributions") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun grossPay(): Optional = grossPay.getOptional("gross_pay") + + /** + * A stable Finch `id` (UUID v4) for an individual in the company + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun netPay(): Optional = netPay.getOptional("net_pay") + + /** + * The payment method. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun paymentMethod(): Optional = paymentMethod.getOptional("payment_method") + + /** + * The array of taxes objects associated with this pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun taxes(): Optional> = taxes.getOptional("taxes") + + /** + * The number of hours worked for this pay period + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun totalHours(): Optional = totalHours.getOptional("total_hours") + + /** + * The type of the payment associated with the pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * Returns the raw JSON value of [earnings]. + * + * Unlike [earnings], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("earnings") @ExcludeMissing fun _earnings(): JsonField> = earnings - /** The array of deductions objects associated with this pay statement. */ + /** + * Returns the raw JSON value of [employeeDeductions]. + * + * Unlike [employeeDeductions], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("employee_deductions") @ExcludeMissing fun _employeeDeductions(): JsonField> = employeeDeductions + /** + * Returns the raw JSON value of [employerContributions]. + * + * Unlike [employerContributions], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("employer_contributions") @ExcludeMissing fun _employerContributions(): JsonField> = employerContributions + /** + * Returns the raw JSON value of [grossPay]. + * + * Unlike [grossPay], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("gross_pay") @ExcludeMissing fun _grossPay(): JsonField = grossPay - /** A stable Finch `id` (UUID v4) for an individual in the company */ + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + /** + * Returns the raw JSON value of [netPay]. + * + * Unlike [netPay], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("net_pay") @ExcludeMissing fun _netPay(): JsonField = netPay - /** The payment method. */ + /** + * Returns the raw JSON value of [paymentMethod]. + * + * Unlike [paymentMethod], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("payment_method") @ExcludeMissing fun _paymentMethod(): JsonField = paymentMethod - /** The array of taxes objects associated with this pay statement. */ + /** + * Returns the raw JSON value of [taxes]. + * + * Unlike [taxes], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("taxes") @ExcludeMissing fun _taxes(): JsonField> = taxes - /** The number of hours worked for this pay period */ + /** + * Returns the raw JSON value of [totalHours]. + * + * Unlike [totalHours], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("total_hours") @ExcludeMissing fun _totalHours(): JsonField = totalHours - /** The type of the payment associated with the pay statement. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): PayStatement = apply { - if (validated) { - return@apply - } - - earnings().ifPresent { it.forEach { it?.validate() } } - employeeDeductions().ifPresent { it.forEach { it?.validate() } } - employerContributions().ifPresent { it.forEach { it?.validate() } } - grossPay().ifPresent { it.validate() } - individualId() - netPay().ifPresent { it.validate() } - paymentMethod() - taxes().ifPresent { it.forEach { it?.validate() } } - totalHours() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [PayStatement]. */ @JvmStatic fun builder() = Builder() } @@ -546,25 +794,29 @@ private constructor( /** The array of earnings objects associated with this pay statement */ fun earnings(earnings: List?) = earnings(JsonField.ofNullable(earnings)) - /** The array of earnings objects associated with this pay statement */ - fun earnings(earnings: Optional>) = earnings(earnings.orElse(null)) + /** Alias for calling [Builder.earnings] with `earnings.orElse(null)`. */ + fun earnings(earnings: Optional>) = earnings(earnings.getOrNull()) - /** The array of earnings objects associated with this pay statement */ + /** + * Sets [Builder.earnings] to an arbitrary JSON value. + * + * You should usually call [Builder.earnings] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun earnings(earnings: JsonField>) = apply { this.earnings = earnings.map { it.toMutableList() } } - /** The array of earnings objects associated with this pay statement */ + /** + * Adds a single [Earning] to [earnings]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addEarning(earning: Earning) = apply { earnings = - (earnings ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(earning) + (earnings ?: JsonField.of(mutableListOf())).also { + checkKnown("earnings", it).add(earning) } } @@ -572,85 +824,130 @@ private constructor( fun employeeDeductions(employeeDeductions: List?) = employeeDeductions(JsonField.ofNullable(employeeDeductions)) - /** The array of deductions objects associated with this pay statement. */ + /** + * Alias for calling [Builder.employeeDeductions] with + * `employeeDeductions.orElse(null)`. + */ fun employeeDeductions(employeeDeductions: Optional>) = - employeeDeductions(employeeDeductions.orElse(null)) + employeeDeductions(employeeDeductions.getOrNull()) - /** The array of deductions objects associated with this pay statement. */ + /** + * Sets [Builder.employeeDeductions] to an arbitrary JSON value. + * + * You should usually call [Builder.employeeDeductions] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun employeeDeductions(employeeDeductions: JsonField>) = apply { this.employeeDeductions = employeeDeductions.map { it.toMutableList() } } - /** The array of deductions objects associated with this pay statement. */ + /** + * Adds a single [EmployeeDeduction] to [employeeDeductions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addEmployeeDeduction(employeeDeduction: EmployeeDeduction) = apply { employeeDeductions = - (employeeDeductions ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(employeeDeduction) + (employeeDeductions ?: JsonField.of(mutableListOf())).also { + checkKnown("employeeDeductions", it).add(employeeDeduction) } } fun employerContributions(employerContributions: List?) = employerContributions(JsonField.ofNullable(employerContributions)) + /** + * Alias for calling [Builder.employerContributions] with + * `employerContributions.orElse(null)`. + */ fun employerContributions( employerContributions: Optional> - ) = employerContributions(employerContributions.orElse(null)) + ) = employerContributions(employerContributions.getOrNull()) + /** + * Sets [Builder.employerContributions] to an arbitrary JSON value. + * + * You should usually call [Builder.employerContributions] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ fun employerContributions( employerContributions: JsonField> ) = apply { this.employerContributions = employerContributions.map { it.toMutableList() } } + /** + * Adds a single [EmployerContribution] to [employerContributions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addEmployerContribution(employerContribution: EmployerContribution) = apply { employerContributions = - (employerContributions ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(employerContribution) + (employerContributions ?: JsonField.of(mutableListOf())).also { + checkKnown("employerContributions", it).add(employerContribution) } } fun grossPay(grossPay: Money?) = grossPay(JsonField.ofNullable(grossPay)) - fun grossPay(grossPay: Optional) = grossPay(grossPay.orElse(null)) + /** Alias for calling [Builder.grossPay] with `grossPay.orElse(null)`. */ + fun grossPay(grossPay: Optional) = grossPay(grossPay.getOrNull()) + /** + * Sets [Builder.grossPay] to an arbitrary JSON value. + * + * You should usually call [Builder.grossPay] with a well-typed [Money] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun grossPay(grossPay: JsonField) = apply { this.grossPay = grossPay } /** A stable Finch `id` (UUID v4) for an individual in the company */ fun individualId(individualId: String) = individualId(JsonField.of(individualId)) - /** A stable Finch `id` (UUID v4) for an individual in the company */ + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } fun netPay(netPay: Money?) = netPay(JsonField.ofNullable(netPay)) - fun netPay(netPay: Optional) = netPay(netPay.orElse(null)) + /** Alias for calling [Builder.netPay] with `netPay.orElse(null)`. */ + fun netPay(netPay: Optional) = netPay(netPay.getOrNull()) + /** + * Sets [Builder.netPay] to an arbitrary JSON value. + * + * You should usually call [Builder.netPay] with a well-typed [Money] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun netPay(netPay: JsonField) = apply { this.netPay = netPay } /** The payment method. */ fun paymentMethod(paymentMethod: PaymentMethod?) = paymentMethod(JsonField.ofNullable(paymentMethod)) - /** The payment method. */ + /** Alias for calling [Builder.paymentMethod] with `paymentMethod.orElse(null)`. */ fun paymentMethod(paymentMethod: Optional) = - paymentMethod(paymentMethod.orElse(null)) + paymentMethod(paymentMethod.getOrNull()) - /** The payment method. */ + /** + * Sets [Builder.paymentMethod] to an arbitrary JSON value. + * + * You should usually call [Builder.paymentMethod] with a well-typed [PaymentMethod] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun paymentMethod(paymentMethod: JsonField) = apply { this.paymentMethod = paymentMethod } @@ -658,49 +955,67 @@ private constructor( /** The array of taxes objects associated with this pay statement. */ fun taxes(taxes: List?) = taxes(JsonField.ofNullable(taxes)) - /** The array of taxes objects associated with this pay statement. */ - fun taxes(taxes: Optional>) = taxes(taxes.orElse(null)) + /** Alias for calling [Builder.taxes] with `taxes.orElse(null)`. */ + fun taxes(taxes: Optional>) = taxes(taxes.getOrNull()) - /** The array of taxes objects associated with this pay statement. */ + /** + * Sets [Builder.taxes] to an arbitrary JSON value. + * + * You should usually call [Builder.taxes] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun taxes(taxes: JsonField>) = apply { this.taxes = taxes.map { it.toMutableList() } } - /** The array of taxes objects associated with this pay statement. */ + /** + * Adds a single [Tax] to [taxes]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addTax(tax: Tax) = apply { taxes = - (taxes ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(tax) + (taxes ?: JsonField.of(mutableListOf())).also { + checkKnown("taxes", it).add(tax) } } /** The number of hours worked for this pay period */ fun totalHours(totalHours: Double?) = totalHours(JsonField.ofNullable(totalHours)) - /** The number of hours worked for this pay period */ + /** + * Alias for [Builder.totalHours]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun totalHours(totalHours: Double) = totalHours(totalHours as Double?) - /** The number of hours worked for this pay period */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun totalHours(totalHours: Optional) = - totalHours(totalHours.orElse(null) as Double?) + /** Alias for calling [Builder.totalHours] with `totalHours.orElse(null)`. */ + fun totalHours(totalHours: Optional) = totalHours(totalHours.getOrNull()) - /** The number of hours worked for this pay period */ + /** + * Sets [Builder.totalHours] to an arbitrary JSON value. + * + * You should usually call [Builder.totalHours] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun totalHours(totalHours: JsonField) = apply { this.totalHours = totalHours } /** The type of the payment associated with the pay statement. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** The type of the payment associated with the pay statement. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** The type of the payment associated with the pay statement. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -722,6 +1037,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [PayStatement]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): PayStatement = PayStatement( (earnings ?: JsonMissing.of()).map { it.toImmutable() }, @@ -734,103 +1054,193 @@ private constructor( (taxes ?: JsonMissing.of()).map { it.toImmutable() }, totalHours, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): PayStatement = apply { + if (validated) { + return@apply + } + + earnings().ifPresent { it.forEach { it?.validate() } } + employeeDeductions().ifPresent { it.forEach { it?.validate() } } + employerContributions().ifPresent { it.forEach { it?.validate() } } + grossPay().ifPresent { it.validate() } + individualId() + netPay().ifPresent { it.validate() } + paymentMethod().ifPresent { it.validate() } + taxes().ifPresent { it.forEach { it?.validate() } } + totalHours() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (earnings.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (employeeDeductions.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } + ?: 0) + + (employerContributions.asKnown().getOrNull()?.sumOf { + (it?.validity() ?: 0).toInt() + } ?: 0) + + (grossPay.asKnown().getOrNull()?.validity() ?: 0) + + (if (individualId.asKnown().isPresent) 1 else 0) + + (netPay.asKnown().getOrNull()?.validity() ?: 0) + + (paymentMethod.asKnown().getOrNull()?.validity() ?: 0) + + (taxes.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (if (totalHours.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Earning - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("attributes") - @ExcludeMissing - private val attributes: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("hours") - @ExcludeMissing - private val hours: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val amount: JsonField, + private val attributes: JsonField, + private val currency: JsonField, + private val hours: JsonField, + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The earnings amount in cents. */ - fun amount(): Optional = Optional.ofNullable(amount.getNullable("amount")) + @JsonCreator + private constructor( + @JsonProperty("amount") @ExcludeMissing amount: JsonField = JsonMissing.of(), + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("hours") @ExcludeMissing hours: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(amount, attributes, currency, hours, name, type, mutableMapOf()) - fun attributes(): Optional = - Optional.ofNullable(attributes.getNullable("attributes")) + /** + * The earnings amount in cents. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") - /** The earnings currency code. */ - fun currency(): Optional = Optional.ofNullable(currency.getNullable("currency")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") + + /** + * The earnings currency code. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") /** * The number of hours associated with this earning. (For salaried employees, this could * be hours per pay period, `0` or `null`, depending on the provider). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun hours(): Optional = Optional.ofNullable(hours.getNullable("hours")) + fun hours(): Optional = hours.getOptional("hours") - /** The exact name of the deduction from the pay statement. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + /** + * The exact name of the deduction from the pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** The type of earning. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The type of earning. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") - /** The earnings amount in cents. */ + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("attributes") @ExcludeMissing fun _attributes(): JsonField = attributes - /** The earnings currency code. */ + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency /** - * The number of hours associated with this earning. (For salaried employees, this could - * be hours per pay period, `0` or `null`, depending on the provider). + * Returns the raw JSON value of [hours]. + * + * Unlike [hours], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("hours") @ExcludeMissing fun _hours(): JsonField = hours - /** The exact name of the deduction from the pay statement. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** The type of earning. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Earning = apply { - if (validated) { - return@apply - } - - amount() - attributes().ifPresent { it.validate() } - currency() - hours() - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Earning]. */ @JvmStatic fun builder() = Builder() } @@ -859,22 +1269,39 @@ private constructor( /** The earnings amount in cents. */ fun amount(amount: Long?) = amount(JsonField.ofNullable(amount)) - /** The earnings amount in cents. */ + /** + * Alias for [Builder.amount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun amount(amount: Long) = amount(amount as Long?) - /** The earnings amount in cents. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun amount(amount: Optional) = amount(amount.orElse(null) as Long?) + /** Alias for calling [Builder.amount] with `amount.orElse(null)`. */ + fun amount(amount: Optional) = amount(amount.getOrNull()) - /** The earnings amount in cents. */ + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun attributes(attributes: Attributes?) = attributes(JsonField.ofNullable(attributes)) + /** Alias for calling [Builder.attributes] with `attributes.orElse(null)`. */ fun attributes(attributes: Optional) = - attributes(attributes.orElse(null)) + attributes(attributes.getOrNull()) + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun attributes(attributes: JsonField) = apply { this.attributes = attributes } @@ -882,10 +1309,16 @@ private constructor( /** The earnings currency code. */ fun currency(currency: String?) = currency(JsonField.ofNullable(currency)) - /** The earnings currency code. */ - fun currency(currency: Optional) = currency(currency.orElse(null)) + /** Alias for calling [Builder.currency] with `currency.orElse(null)`. */ + fun currency(currency: Optional) = currency(currency.getOrNull()) - /** The earnings currency code. */ + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } /** @@ -895,40 +1328,52 @@ private constructor( fun hours(hours: Double?) = hours(JsonField.ofNullable(hours)) /** - * The number of hours associated with this earning. (For salaried employees, this - * could be hours per pay period, `0` or `null`, depending on the provider). + * Alias for [Builder.hours]. + * + * This unboxed primitive overload exists for backwards compatibility. */ fun hours(hours: Double) = hours(hours as Double?) - /** - * The number of hours associated with this earning. (For salaried employees, this - * could be hours per pay period, `0` or `null`, depending on the provider). - */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun hours(hours: Optional) = hours(hours.orElse(null) as Double?) + /** Alias for calling [Builder.hours] with `hours.orElse(null)`. */ + fun hours(hours: Optional) = hours(hours.getOrNull()) /** - * The number of hours associated with this earning. (For salaried employees, this - * could be hours per pay period, `0` or `null`, depending on the provider). + * Sets [Builder.hours] to an arbitrary JSON value. + * + * You should usually call [Builder.hours] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. */ fun hours(hours: JsonField) = apply { this.hours = hours } /** The exact name of the deduction from the pay statement. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The exact name of the deduction from the pay statement. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The exact name of the deduction from the pay statement. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun name(name: JsonField) = apply { this.name = name } /** The type of earning. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** The type of earning. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** The type of earning. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -953,6 +1398,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Earning]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Earning = Earning( amount, @@ -961,47 +1411,93 @@ private constructor( hours, name, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Earning = apply { + if (validated) { + return@apply + } + + amount() + attributes().ifPresent { it.validate() } + currency() + hours() + name() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (hours.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Attributes - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Attributes = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Attributes]. */ @JvmStatic fun builder() = Builder() } @@ -1019,6 +1515,13 @@ private constructor( fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata } fun additionalProperties(additionalProperties: Map) = apply { @@ -1043,57 +1546,91 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Attributes = - Attributes(metadata, additionalProperties.toImmutable()) + Attributes(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } - @NoAutoDetect + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + class Metadata - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + /** * The metadata to be attached to the entity by existing rules. It is a * key-value pairs where the values can be of any type (string, number, boolean, * object, array, etc.). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** - * The metadata to be attached to the entity by existing rules. It is a - * key-value pairs where the values can be of any type (string, number, boolean, - * object, array, etc.). + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an + * unexpected type. */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Metadata]. */ @JvmStatic fun builder() = Builder() } @@ -1118,9 +1655,11 @@ private constructor( fun metadata(metadata: InnerMetadata) = metadata(JsonField.of(metadata)) /** - * The metadata to be attached to the entity by existing rules. It is a - * key-value pairs where the values can be of any type (string, number, - * boolean, object, array, etc.). + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed + * [InnerMetadata] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata @@ -1148,42 +1687,67 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Metadata = - Metadata(metadata, additionalProperties.toImmutable()) + Metadata(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + /** * The metadata to be attached to the entity by existing rules. It is a * key-value pairs where the values can be of any type (string, number, boolean, * object, array, etc.). */ - @NoAutoDetect class InnerMetadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): InnerMetadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [InnerMetadata]. + */ @JvmStatic fun builder() = Builder() } @@ -1221,10 +1785,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [InnerMetadata]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): InnerMetadata = InnerMetadata(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): InnerMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1436,6 +2036,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -1467,93 +2094,144 @@ private constructor( "Earning{amount=$amount, attributes=$attributes, currency=$currency, hours=$hours, name=$name, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class EmployeeDeduction - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("attributes") - @ExcludeMissing - private val attributes: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("pre_tax") - @ExcludeMissing - private val preTax: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val amount: JsonField, + private val attributes: JsonField, + private val currency: JsonField, + private val name: JsonField, + private val preTax: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The deduction amount in cents. */ - fun amount(): Optional = Optional.ofNullable(amount.getNullable("amount")) + @JsonCreator + private constructor( + @JsonProperty("amount") @ExcludeMissing amount: JsonField = JsonMissing.of(), + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("pre_tax") + @ExcludeMissing + preTax: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(amount, attributes, currency, name, preTax, type, mutableMapOf()) + + /** + * The deduction amount in cents. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") - fun attributes(): Optional = - Optional.ofNullable(attributes.getNullable("attributes")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") - /** The deduction currency. */ - fun currency(): Optional = Optional.ofNullable(currency.getNullable("currency")) + /** + * The deduction currency. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") - /** The deduction name from the pay statement. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + /** + * The deduction name from the pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** Boolean indicating if the deduction is pre-tax. */ - fun preTax(): Optional = Optional.ofNullable(preTax.getNullable("pre_tax")) + /** + * Boolean indicating if the deduction is pre-tax. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun preTax(): Optional = preTax.getOptional("pre_tax") - /** Type of benefit. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * Type of benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") - /** The deduction amount in cents. */ + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("attributes") @ExcludeMissing fun _attributes(): JsonField = attributes - /** The deduction currency. */ + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency - /** The deduction name from the pay statement. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** Boolean indicating if the deduction is pre-tax. */ + /** + * Returns the raw JSON value of [preTax]. + * + * Unlike [preTax], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("pre_tax") @ExcludeMissing fun _preTax(): JsonField = preTax - /** Type of benefit. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): EmployeeDeduction = apply { - if (validated) { - return@apply - } - - amount() - attributes().ifPresent { it.validate() } - currency() - name() - preTax() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [EmployeeDeduction]. + */ @JvmStatic fun builder() = Builder() } @@ -1582,22 +2260,39 @@ private constructor( /** The deduction amount in cents. */ fun amount(amount: Long?) = amount(JsonField.ofNullable(amount)) - /** The deduction amount in cents. */ + /** + * Alias for [Builder.amount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun amount(amount: Long) = amount(amount as Long?) - /** The deduction amount in cents. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun amount(amount: Optional) = amount(amount.orElse(null) as Long?) + /** Alias for calling [Builder.amount] with `amount.orElse(null)`. */ + fun amount(amount: Optional) = amount(amount.getOrNull()) - /** The deduction amount in cents. */ + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun attributes(attributes: Attributes?) = attributes(JsonField.ofNullable(attributes)) + /** Alias for calling [Builder.attributes] with `attributes.orElse(null)`. */ fun attributes(attributes: Optional) = - attributes(attributes.orElse(null)) + attributes(attributes.getOrNull()) + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun attributes(attributes: JsonField) = apply { this.attributes = attributes } @@ -1605,41 +2300,68 @@ private constructor( /** The deduction currency. */ fun currency(currency: String?) = currency(JsonField.ofNullable(currency)) - /** The deduction currency. */ - fun currency(currency: Optional) = currency(currency.orElse(null)) + /** Alias for calling [Builder.currency] with `currency.orElse(null)`. */ + fun currency(currency: Optional) = currency(currency.getOrNull()) - /** The deduction currency. */ + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } /** The deduction name from the pay statement. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The deduction name from the pay statement. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The deduction name from the pay statement. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun name(name: JsonField) = apply { this.name = name } /** Boolean indicating if the deduction is pre-tax. */ fun preTax(preTax: Boolean?) = preTax(JsonField.ofNullable(preTax)) - /** Boolean indicating if the deduction is pre-tax. */ + /** + * Alias for [Builder.preTax]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun preTax(preTax: Boolean) = preTax(preTax as Boolean?) - /** Boolean indicating if the deduction is pre-tax. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun preTax(preTax: Optional) = preTax(preTax.orElse(null) as Boolean?) + /** Alias for calling [Builder.preTax] with `preTax.orElse(null)`. */ + fun preTax(preTax: Optional) = preTax(preTax.getOrNull()) - /** Boolean indicating if the deduction is pre-tax. */ + /** + * Sets [Builder.preTax] to an arbitrary JSON value. + * + * You should usually call [Builder.preTax] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun preTax(preTax: JsonField) = apply { this.preTax = preTax } /** Type of benefit. */ fun type(type: BenefitType?) = type(JsonField.ofNullable(type)) - /** Type of benefit. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** Type of benefit. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [BenefitType] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -1664,6 +2386,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [EmployeeDeduction]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): EmployeeDeduction = EmployeeDeduction( amount, @@ -1672,47 +2399,93 @@ private constructor( name, preTax, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): EmployeeDeduction = apply { + if (validated) { + return@apply + } + + amount() + attributes().ifPresent { it.validate() } + currency() + name() + preTax() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (preTax.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Attributes - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Attributes = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Attributes]. */ @JvmStatic fun builder() = Builder() } @@ -1730,6 +2503,13 @@ private constructor( fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata } fun additionalProperties(additionalProperties: Map) = apply { @@ -1754,57 +2534,91 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Attributes = - Attributes(metadata, additionalProperties.toImmutable()) + Attributes(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } - @NoAutoDetect + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + class Metadata - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + /** * The metadata to be attached to the entity by existing rules. It is a * key-value pairs where the values can be of any type (string, number, boolean, * object, array, etc.). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** - * The metadata to be attached to the entity by existing rules. It is a - * key-value pairs where the values can be of any type (string, number, boolean, - * object, array, etc.). + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an + * unexpected type. */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Metadata]. */ @JvmStatic fun builder() = Builder() } @@ -1829,9 +2643,11 @@ private constructor( fun metadata(metadata: InnerMetadata) = metadata(JsonField.of(metadata)) /** - * The metadata to be attached to the entity by existing rules. It is a - * key-value pairs where the values can be of any type (string, number, - * boolean, object, array, etc.). + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed + * [InnerMetadata] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata @@ -1859,42 +2675,67 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Metadata = - Metadata(metadata, additionalProperties.toImmutable()) + Metadata(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + /** * The metadata to be attached to the entity by existing rules. It is a * key-value pairs where the values can be of any type (string, number, boolean, * object, array, etc.). */ - @NoAutoDetect class InnerMetadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): InnerMetadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [InnerMetadata]. + */ @JvmStatic fun builder() = Builder() } @@ -1932,10 +2773,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [InnerMetadata]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): InnerMetadata = InnerMetadata(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): InnerMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2008,83 +2885,125 @@ private constructor( "EmployeeDeduction{amount=$amount, attributes=$attributes, currency=$currency, name=$name, preTax=$preTax, type=$type, additionalProperties=$additionalProperties}" } - @NoAutoDetect class EmployerContribution - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("attributes") - @ExcludeMissing - private val attributes: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val amount: JsonField, + private val attributes: JsonField, + private val currency: JsonField, + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The contribution amount in cents. */ - fun amount(): Optional = Optional.ofNullable(amount.getNullable("amount")) + @JsonCreator + private constructor( + @JsonProperty("amount") @ExcludeMissing amount: JsonField = JsonMissing.of(), + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") + @ExcludeMissing + type: JsonField = JsonMissing.of(), + ) : this(amount, attributes, currency, name, type, mutableMapOf()) + + /** + * The contribution amount in cents. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") - fun attributes(): Optional = - Optional.ofNullable(attributes.getNullable("attributes")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") - /** The contribution currency. */ - fun currency(): Optional = Optional.ofNullable(currency.getNullable("currency")) + /** + * The contribution currency. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") - /** The contribution name from the pay statement. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + /** + * The contribution name from the pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** Type of benefit. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * Type of benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") - /** The contribution amount in cents. */ + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("attributes") @ExcludeMissing fun _attributes(): JsonField = attributes - /** The contribution currency. */ + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency - /** The contribution name from the pay statement. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** Type of benefit. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): EmployerContribution = apply { - if (validated) { - return@apply - } - - amount() - attributes().ifPresent { it.validate() } - currency() - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [EmployerContribution]. + */ @JvmStatic fun builder() = Builder() } @@ -2111,22 +3030,39 @@ private constructor( /** The contribution amount in cents. */ fun amount(amount: Long?) = amount(JsonField.ofNullable(amount)) - /** The contribution amount in cents. */ + /** + * Alias for [Builder.amount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun amount(amount: Long) = amount(amount as Long?) - /** The contribution amount in cents. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun amount(amount: Optional) = amount(amount.orElse(null) as Long?) + /** Alias for calling [Builder.amount] with `amount.orElse(null)`. */ + fun amount(amount: Optional) = amount(amount.getOrNull()) - /** The contribution amount in cents. */ + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun attributes(attributes: Attributes?) = attributes(JsonField.ofNullable(attributes)) + /** Alias for calling [Builder.attributes] with `attributes.orElse(null)`. */ fun attributes(attributes: Optional) = - attributes(attributes.orElse(null)) + attributes(attributes.getOrNull()) + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun attributes(attributes: JsonField) = apply { this.attributes = attributes } @@ -2134,28 +3070,46 @@ private constructor( /** The contribution currency. */ fun currency(currency: String?) = currency(JsonField.ofNullable(currency)) - /** The contribution currency. */ - fun currency(currency: Optional) = currency(currency.orElse(null)) + /** Alias for calling [Builder.currency] with `currency.orElse(null)`. */ + fun currency(currency: Optional) = currency(currency.getOrNull()) - /** The contribution currency. */ + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } /** The contribution name from the pay statement. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The contribution name from the pay statement. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The contribution name from the pay statement. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun name(name: JsonField) = apply { this.name = name } /** Type of benefit. */ fun type(type: BenefitType?) = type(JsonField.ofNullable(type)) - /** Type of benefit. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** Type of benefit. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [BenefitType] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -2180,6 +3134,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [EmployerContribution]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): EmployerContribution = EmployerContribution( amount, @@ -2187,47 +3146,91 @@ private constructor( currency, name, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): EmployerContribution = apply { + if (validated) { + return@apply + } + + amount() + attributes().ifPresent { it.validate() } + currency() + name() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Attributes - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Attributes = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Attributes]. */ @JvmStatic fun builder() = Builder() } @@ -2245,6 +3248,13 @@ private constructor( fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata } fun additionalProperties(additionalProperties: Map) = apply { @@ -2269,57 +3279,91 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Attributes = - Attributes(metadata, additionalProperties.toImmutable()) + Attributes(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } - @NoAutoDetect + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + class Metadata - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + /** * The metadata to be attached to the entity by existing rules. It is a * key-value pairs where the values can be of any type (string, number, boolean, * object, array, etc.). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** - * The metadata to be attached to the entity by existing rules. It is a - * key-value pairs where the values can be of any type (string, number, boolean, - * object, array, etc.). + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an + * unexpected type. */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Metadata]. */ @JvmStatic fun builder() = Builder() } @@ -2344,9 +3388,11 @@ private constructor( fun metadata(metadata: InnerMetadata) = metadata(JsonField.of(metadata)) /** - * The metadata to be attached to the entity by existing rules. It is a - * key-value pairs where the values can be of any type (string, number, - * boolean, object, array, etc.). + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed + * [InnerMetadata] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata @@ -2374,42 +3420,67 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Metadata = - Metadata(metadata, additionalProperties.toImmutable()) + Metadata(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + /** * The metadata to be attached to the entity by existing rules. It is a * key-value pairs where the values can be of any type (string, number, boolean, * object, array, etc.). */ - @NoAutoDetect class InnerMetadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): InnerMetadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [InnerMetadata]. + */ @JvmStatic fun builder() = Builder() } @@ -2447,10 +3518,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [InnerMetadata]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): InnerMetadata = InnerMetadata(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): InnerMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2615,6 +3722,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): PaymentMethod = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -2628,94 +3762,141 @@ private constructor( override fun toString() = value.toString() } - @NoAutoDetect class Tax - @JsonCreator private constructor( - @JsonProperty("amount") - @ExcludeMissing - private val amount: JsonField = JsonMissing.of(), - @JsonProperty("attributes") - @ExcludeMissing - private val attributes: JsonField = JsonMissing.of(), - @JsonProperty("currency") - @ExcludeMissing - private val currency: JsonField = JsonMissing.of(), - @JsonProperty("employer") - @ExcludeMissing - private val employer: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val amount: JsonField, + private val attributes: JsonField, + private val currency: JsonField, + private val employer: JsonField, + private val name: JsonField, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** The tax amount in cents. */ - fun amount(): Optional = Optional.ofNullable(amount.getNullable("amount")) + @JsonCreator + private constructor( + @JsonProperty("amount") @ExcludeMissing amount: JsonField = JsonMissing.of(), + @JsonProperty("attributes") + @ExcludeMissing + attributes: JsonField = JsonMissing.of(), + @JsonProperty("currency") + @ExcludeMissing + currency: JsonField = JsonMissing.of(), + @JsonProperty("employer") + @ExcludeMissing + employer: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this(amount, attributes, currency, employer, name, type, mutableMapOf()) + + /** + * The tax amount in cents. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun amount(): Optional = amount.getOptional("amount") - fun attributes(): Optional = - Optional.ofNullable(attributes.getNullable("attributes")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun attributes(): Optional = attributes.getOptional("attributes") - /** The currency code. */ - fun currency(): Optional = Optional.ofNullable(currency.getNullable("currency")) + /** + * The currency code. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun currency(): Optional = currency.getOptional("currency") - /** `true` if the amount is paid by the employers. */ - fun employer(): Optional = - Optional.ofNullable(employer.getNullable("employer")) + /** + * `true` if the amount is paid by the employers. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun employer(): Optional = employer.getOptional("employer") - /** The exact name of tax from the pay statement. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + /** + * The exact name of tax from the pay statement. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") - /** The type of taxes. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * The type of taxes. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") - /** The tax amount in cents. */ + /** + * Returns the raw JSON value of [amount]. + * + * Unlike [amount], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("amount") @ExcludeMissing fun _amount(): JsonField = amount + /** + * Returns the raw JSON value of [attributes]. + * + * Unlike [attributes], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("attributes") @ExcludeMissing fun _attributes(): JsonField = attributes - /** The currency code. */ + /** + * Returns the raw JSON value of [currency]. + * + * Unlike [currency], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("currency") @ExcludeMissing fun _currency(): JsonField = currency - /** `true` if the amount is paid by the employers. */ + /** + * Returns the raw JSON value of [employer]. + * + * Unlike [employer], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("employer") @ExcludeMissing fun _employer(): JsonField = employer - /** The exact name of tax from the pay statement. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name - /** The type of taxes. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Tax = apply { - if (validated) { - return@apply - } - - amount() - attributes().ifPresent { it.validate() } - currency() - employer() - name() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Tax]. */ @JvmStatic fun builder() = Builder() } @@ -2744,22 +3925,39 @@ private constructor( /** The tax amount in cents. */ fun amount(amount: Long?) = amount(JsonField.ofNullable(amount)) - /** The tax amount in cents. */ + /** + * Alias for [Builder.amount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun amount(amount: Long) = amount(amount as Long?) - /** The tax amount in cents. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun amount(amount: Optional) = amount(amount.orElse(null) as Long?) + /** Alias for calling [Builder.amount] with `amount.orElse(null)`. */ + fun amount(amount: Optional) = amount(amount.getOrNull()) - /** The tax amount in cents. */ + /** + * Sets [Builder.amount] to an arbitrary JSON value. + * + * You should usually call [Builder.amount] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun amount(amount: JsonField) = apply { this.amount = amount } fun attributes(attributes: Attributes?) = attributes(JsonField.ofNullable(attributes)) + /** Alias for calling [Builder.attributes] with `attributes.orElse(null)`. */ fun attributes(attributes: Optional) = - attributes(attributes.orElse(null)) + attributes(attributes.getOrNull()) + /** + * Sets [Builder.attributes] to an arbitrary JSON value. + * + * You should usually call [Builder.attributes] with a well-typed [Attributes] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun attributes(attributes: JsonField) = apply { this.attributes = attributes } @@ -2767,42 +3965,68 @@ private constructor( /** The currency code. */ fun currency(currency: String?) = currency(JsonField.ofNullable(currency)) - /** The currency code. */ - fun currency(currency: Optional) = currency(currency.orElse(null)) + /** Alias for calling [Builder.currency] with `currency.orElse(null)`. */ + fun currency(currency: Optional) = currency(currency.getOrNull()) - /** The currency code. */ + /** + * Sets [Builder.currency] to an arbitrary JSON value. + * + * You should usually call [Builder.currency] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun currency(currency: JsonField) = apply { this.currency = currency } /** `true` if the amount is paid by the employers. */ fun employer(employer: Boolean?) = employer(JsonField.ofNullable(employer)) - /** `true` if the amount is paid by the employers. */ + /** + * Alias for [Builder.employer]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun employer(employer: Boolean) = employer(employer as Boolean?) - /** `true` if the amount is paid by the employers. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun employer(employer: Optional) = - employer(employer.orElse(null) as Boolean?) + /** Alias for calling [Builder.employer] with `employer.orElse(null)`. */ + fun employer(employer: Optional) = employer(employer.getOrNull()) - /** `true` if the amount is paid by the employers. */ + /** + * Sets [Builder.employer] to an arbitrary JSON value. + * + * You should usually call [Builder.employer] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun employer(employer: JsonField) = apply { this.employer = employer } /** The exact name of tax from the pay statement. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** The exact name of tax from the pay statement. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** The exact name of tax from the pay statement. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun name(name: JsonField) = apply { this.name = name } /** The type of taxes. */ fun type(type: Type?) = type(JsonField.ofNullable(type)) - /** The type of taxes. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** The type of taxes. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -2827,6 +4051,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Tax]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Tax = Tax( amount, @@ -2835,47 +4064,93 @@ private constructor( employer, name, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } - @NoAutoDetect + private var validated: Boolean = false + + fun validate(): Tax = apply { + if (validated) { + return@apply + } + + amount() + attributes().ifPresent { it.validate() } + currency() + employer() + name() + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amount.asKnown().isPresent) 1 else 0) + + (attributes.asKnown().getOrNull()?.validity() ?: 0) + + (if (currency.asKnown().isPresent) 1 else 0) + + (if (employer.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class Attributes - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Attributes = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Attributes]. */ @JvmStatic fun builder() = Builder() } @@ -2893,6 +4168,13 @@ private constructor( fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata } fun additionalProperties(additionalProperties: Map) = apply { @@ -2917,57 +4199,91 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Attributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Attributes = - Attributes(metadata, additionalProperties.toImmutable()) + Attributes(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Attributes = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } - @NoAutoDetect + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + class Metadata - @JsonCreator private constructor( - @JsonProperty("metadata") - @ExcludeMissing - private val metadata: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val metadata: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("metadata") + @ExcludeMissing + metadata: JsonField = JsonMissing.of() + ) : this(metadata, mutableMapOf()) + /** * The metadata to be attached to the entity by existing rules. It is a * key-value pairs where the values can be of any type (string, number, boolean, * object, array, etc.). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type + * (e.g. if the server responded with an unexpected value). */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + fun metadata(): Optional = metadata.getOptional("metadata") /** - * The metadata to be attached to the entity by existing rules. It is a - * key-value pairs where the values can be of any type (string, number, boolean, - * object, array, etc.). + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an + * unexpected type. */ @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Metadata = apply { - if (validated) { - return@apply - } - - metadata().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Metadata]. */ @JvmStatic fun builder() = Builder() } @@ -2992,9 +4308,11 @@ private constructor( fun metadata(metadata: InnerMetadata) = metadata(JsonField.of(metadata)) /** - * The metadata to be attached to the entity by existing rules. It is a - * key-value pairs where the values can be of any type (string, number, - * boolean, object, array, etc.). + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed + * [InnerMetadata] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. */ fun metadata(metadata: JsonField) = apply { this.metadata = metadata @@ -3022,42 +4340,67 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Metadata = - Metadata(metadata, additionalProperties.toImmutable()) + Metadata(metadata, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + metadata().ifPresent { it.validate() } + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = (metadata.asKnown().getOrNull()?.validity() ?: 0) + /** * The metadata to be attached to the entity by existing rules. It is a * key-value pairs where the values can be of any type (string, number, boolean, * object, array, etc.). */ - @NoAutoDetect class InnerMetadata @JsonCreator private constructor( - @JsonAnySetter - private val additionalProperties: Map = - immutableEmptyMap() + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - private var validated: Boolean = false - - fun validate(): InnerMetadata = apply { - if (validated) { - return@apply - } - - validated = true - } - fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [InnerMetadata]. + */ @JvmStatic fun builder() = Builder() } @@ -3095,10 +4438,46 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [InnerMetadata]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + */ fun build(): InnerMetadata = InnerMetadata(additionalProperties.toImmutable()) } + private var validated: Boolean = false + + fun validate(): InnerMetadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this + * object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> + !value.isNull() && !value.isMissing() + } + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3256,6 +4635,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -3381,6 +4787,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SessionNewResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SessionNewResponse.kt index 43a46246..621f3ceb 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SessionNewResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SessionNewResponse.kt @@ -10,57 +10,79 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects -@NoAutoDetect class SessionNewResponse -@JsonCreator private constructor( - @JsonProperty("connect_url") - @ExcludeMissing - private val connectUrl: JsonField = JsonMissing.of(), - @JsonProperty("session_id") - @ExcludeMissing - private val sessionId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val connectUrl: JsonField, + private val sessionId: JsonField, + private val additionalProperties: MutableMap, ) { - /** The Connect URL to redirect the user to for authentication */ + @JsonCreator + private constructor( + @JsonProperty("connect_url") + @ExcludeMissing + connectUrl: JsonField = JsonMissing.of(), + @JsonProperty("session_id") @ExcludeMissing sessionId: JsonField = JsonMissing.of(), + ) : this(connectUrl, sessionId, mutableMapOf()) + + /** + * The Connect URL to redirect the user to for authentication + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun connectUrl(): String = connectUrl.getRequired("connect_url") - /** The unique identifier for the created connect session */ + /** + * The unique identifier for the created connect session + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun sessionId(): String = sessionId.getRequired("session_id") - /** The Connect URL to redirect the user to for authentication */ + /** + * Returns the raw JSON value of [connectUrl]. + * + * Unlike [connectUrl], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connect_url") @ExcludeMissing fun _connectUrl(): JsonField = connectUrl - /** The unique identifier for the created connect session */ + /** + * Returns the raw JSON value of [sessionId]. + * + * Unlike [sessionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("session_id") @ExcludeMissing fun _sessionId(): JsonField = sessionId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SessionNewResponse = apply { - if (validated) { - return@apply - } - - connectUrl() - sessionId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [SessionNewResponse]. + * + * The following fields are required: + * ```java + * .connectUrl() + * .sessionId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -81,13 +103,25 @@ private constructor( /** The Connect URL to redirect the user to for authentication */ fun connectUrl(connectUrl: String) = connectUrl(JsonField.of(connectUrl)) - /** The Connect URL to redirect the user to for authentication */ + /** + * Sets [Builder.connectUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.connectUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectUrl(connectUrl: JsonField) = apply { this.connectUrl = connectUrl } /** The unique identifier for the created connect session */ fun sessionId(sessionId: String) = sessionId(JsonField.of(sessionId)) - /** The unique identifier for the created connect session */ + /** + * Sets [Builder.sessionId] to an arbitrary JSON value. + * + * You should usually call [Builder.sessionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun sessionId(sessionId: JsonField) = apply { this.sessionId = sessionId } fun additionalProperties(additionalProperties: Map) = apply { @@ -109,14 +143,57 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SessionNewResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .connectUrl() + * .sessionId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): SessionNewResponse = SessionNewResponse( checkRequired("connectUrl", connectUrl), checkRequired("sessionId", sessionId), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): SessionNewResponse = apply { + if (validated) { + return@apply + } + + connectUrl() + sessionId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (connectUrl.asKnown().isPresent) 1 else 0) + + (if (sessionId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SessionReauthenticateResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SessionReauthenticateResponse.kt index b6fe7686..f3a6a435 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SessionReauthenticateResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SessionReauthenticateResponse.kt @@ -10,57 +10,80 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects -@NoAutoDetect class SessionReauthenticateResponse -@JsonCreator private constructor( - @JsonProperty("connect_url") - @ExcludeMissing - private val connectUrl: JsonField = JsonMissing.of(), - @JsonProperty("session_id") - @ExcludeMissing - private val sessionId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val connectUrl: JsonField, + private val sessionId: JsonField, + private val additionalProperties: MutableMap, ) { - /** The Connect URL to redirect the user to for reauthentication */ + @JsonCreator + private constructor( + @JsonProperty("connect_url") + @ExcludeMissing + connectUrl: JsonField = JsonMissing.of(), + @JsonProperty("session_id") @ExcludeMissing sessionId: JsonField = JsonMissing.of(), + ) : this(connectUrl, sessionId, mutableMapOf()) + + /** + * The Connect URL to redirect the user to for reauthentication + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun connectUrl(): String = connectUrl.getRequired("connect_url") - /** The unique identifier for the created connect session */ + /** + * The unique identifier for the created connect session + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun sessionId(): String = sessionId.getRequired("session_id") - /** The Connect URL to redirect the user to for reauthentication */ + /** + * Returns the raw JSON value of [connectUrl]. + * + * Unlike [connectUrl], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("connect_url") @ExcludeMissing fun _connectUrl(): JsonField = connectUrl - /** The unique identifier for the created connect session */ + /** + * Returns the raw JSON value of [sessionId]. + * + * Unlike [sessionId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("session_id") @ExcludeMissing fun _sessionId(): JsonField = sessionId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SessionReauthenticateResponse = apply { - if (validated) { - return@apply - } - - connectUrl() - sessionId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of + * [SessionReauthenticateResponse]. + * + * The following fields are required: + * ```java + * .connectUrl() + * .sessionId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -81,13 +104,25 @@ private constructor( /** The Connect URL to redirect the user to for reauthentication */ fun connectUrl(connectUrl: String) = connectUrl(JsonField.of(connectUrl)) - /** The Connect URL to redirect the user to for reauthentication */ + /** + * Sets [Builder.connectUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.connectUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun connectUrl(connectUrl: JsonField) = apply { this.connectUrl = connectUrl } /** The unique identifier for the created connect session */ fun sessionId(sessionId: String) = sessionId(JsonField.of(sessionId)) - /** The unique identifier for the created connect session */ + /** + * Sets [Builder.sessionId] to an arbitrary JSON value. + * + * You should usually call [Builder.sessionId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun sessionId(sessionId: JsonField) = apply { this.sessionId = sessionId } fun additionalProperties(additionalProperties: Map) = apply { @@ -109,14 +144,57 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SessionReauthenticateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .connectUrl() + * .sessionId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): SessionReauthenticateResponse = SessionReauthenticateResponse( checkRequired("connectUrl", connectUrl), checkRequired("sessionId", sessionId), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): SessionReauthenticateResponse = apply { + if (validated) { + return@apply + } + + connectUrl() + sessionId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (connectUrl.asKnown().isPresent) 1 else 0) + + (if (sessionId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SupportPerBenefitType.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SupportPerBenefitType.kt index 34774cef..03902715 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SupportPerBenefitType.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SupportPerBenefitType.kt @@ -10,59 +10,77 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class SupportPerBenefitType -@JsonCreator private constructor( - @JsonProperty("company_benefits") - @ExcludeMissing - private val companyBenefits: JsonField = JsonMissing.of(), - @JsonProperty("individual_benefits") - @ExcludeMissing - private val individualBenefits: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val companyBenefits: JsonField, + private val individualBenefits: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("company_benefits") + @ExcludeMissing + companyBenefits: JsonField = JsonMissing.of(), + @JsonProperty("individual_benefits") + @ExcludeMissing + individualBenefits: JsonField = JsonMissing.of(), + ) : this(companyBenefits, individualBenefits, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun companyBenefits(): Optional = - Optional.ofNullable(companyBenefits.getNullable("company_benefits")) + companyBenefits.getOptional("company_benefits") + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun individualBenefits(): Optional = - Optional.ofNullable(individualBenefits.getNullable("individual_benefits")) + individualBenefits.getOptional("individual_benefits") + /** + * Returns the raw JSON value of [companyBenefits]. + * + * Unlike [companyBenefits], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("company_benefits") @ExcludeMissing fun _companyBenefits(): JsonField = companyBenefits + /** + * Returns the raw JSON value of [individualBenefits]. + * + * Unlike [individualBenefits], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("individual_benefits") @ExcludeMissing fun _individualBenefits(): JsonField = individualBenefits + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportPerBenefitType = apply { - if (validated) { - return@apply - } - - companyBenefits().ifPresent { it.validate() } - individualBenefits().ifPresent { it.validate() } - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [SupportPerBenefitType]. */ @JvmStatic fun builder() = Builder() } @@ -83,6 +101,13 @@ private constructor( fun companyBenefits(companyBenefits: OperationSupportMatrix) = companyBenefits(JsonField.of(companyBenefits)) + /** + * Sets [Builder.companyBenefits] to an arbitrary JSON value. + * + * You should usually call [Builder.companyBenefits] with a well-typed + * [OperationSupportMatrix] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ fun companyBenefits(companyBenefits: JsonField) = apply { this.companyBenefits = companyBenefits } @@ -90,6 +115,13 @@ private constructor( fun individualBenefits(individualBenefits: OperationSupportMatrix) = individualBenefits(JsonField.of(individualBenefits)) + /** + * Sets [Builder.individualBenefits] to an arbitrary JSON value. + * + * You should usually call [Builder.individualBenefits] with a well-typed + * [OperationSupportMatrix] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ fun individualBenefits(individualBenefits: JsonField) = apply { this.individualBenefits = individualBenefits } @@ -113,14 +145,49 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportPerBenefitType]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportPerBenefitType = SupportPerBenefitType( companyBenefits, individualBenefits, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): SupportPerBenefitType = apply { + if (validated) { + return@apply + } + + companyBenefits().ifPresent { it.validate() } + individualBenefits().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (companyBenefits.asKnown().getOrNull()?.validity() ?: 0) + + (individualBenefits.asKnown().getOrNull()?.validity() ?: 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SupportedBenefit.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SupportedBenefit.kt index b23e5480..f16b14b7 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SupportedBenefit.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/SupportedBenefit.kt @@ -11,144 +11,212 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap +import com.tryfinch.api.core.checkKnown import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class SupportedBenefit -@JsonCreator private constructor( - @JsonProperty("annual_maximum") - @ExcludeMissing - private val annualMaximum: JsonField = JsonMissing.of(), - @JsonProperty("catch_up") - @ExcludeMissing - private val catchUp: JsonField = JsonMissing.of(), - @JsonProperty("company_contribution") - @ExcludeMissing - private val companyContribution: JsonField> = JsonMissing.of(), - @JsonProperty("description") - @ExcludeMissing - private val description: JsonField = JsonMissing.of(), - @JsonProperty("employee_deduction") - @ExcludeMissing - private val employeeDeduction: JsonField> = JsonMissing.of(), - @JsonProperty("frequencies") - @ExcludeMissing - private val frequencies: JsonField> = JsonMissing.of(), - @JsonProperty("hsa_contribution_limit") - @ExcludeMissing - private val hsaContributionLimit: JsonField> = JsonMissing.of(), - @JsonProperty("type") - @ExcludeMissing - private val type: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val annualMaximum: JsonField, + private val catchUp: JsonField, + private val companyContribution: JsonField>, + private val description: JsonField, + private val employeeDeduction: JsonField>, + private val frequencies: JsonField>, + private val hsaContributionLimit: JsonField>, + private val type: JsonField, + private val additionalProperties: MutableMap, ) { - /** Whether the provider supports an annual maximum for this benefit. */ - fun annualMaximum(): Optional = - Optional.ofNullable(annualMaximum.getNullable("annual_maximum")) + @JsonCreator + private constructor( + @JsonProperty("annual_maximum") + @ExcludeMissing + annualMaximum: JsonField = JsonMissing.of(), + @JsonProperty("catch_up") @ExcludeMissing catchUp: JsonField = JsonMissing.of(), + @JsonProperty("company_contribution") + @ExcludeMissing + companyContribution: JsonField> = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), + @JsonProperty("employee_deduction") + @ExcludeMissing + employeeDeduction: JsonField> = JsonMissing.of(), + @JsonProperty("frequencies") + @ExcludeMissing + frequencies: JsonField> = JsonMissing.of(), + @JsonProperty("hsa_contribution_limit") + @ExcludeMissing + hsaContributionLimit: JsonField> = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + ) : this( + annualMaximum, + catchUp, + companyContribution, + description, + employeeDeduction, + frequencies, + hsaContributionLimit, + type, + mutableMapOf(), + ) + + /** + * Whether the provider supports an annual maximum for this benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun annualMaximum(): Optional = annualMaximum.getOptional("annual_maximum") /** * Whether the provider supports catch up for this benefit. This field will only be true for * retirement benefits. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun catchUp(): Optional = Optional.ofNullable(catchUp.getNullable("catch_up")) + fun catchUp(): Optional = catchUp.getOptional("catch_up") - /** Supported contribution types. An empty array indicates contributions are not supported. */ + /** + * Supported contribution types. An empty array indicates contributions are not supported. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun companyContribution(): Optional> = - Optional.ofNullable(companyContribution.getNullable("company_contribution")) + companyContribution.getOptional("company_contribution") - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") - /** Supported deduction types. An empty array indicates deductions are not supported. */ + /** + * Supported deduction types. An empty array indicates deductions are not supported. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun employeeDeduction(): Optional> = - Optional.ofNullable(employeeDeduction.getNullable("employee_deduction")) + employeeDeduction.getOptional("employee_deduction") - /** The list of frequencies supported by the provider for this benefit */ - fun frequencies(): Optional> = - Optional.ofNullable(frequencies.getNullable("frequencies")) + /** + * The list of frequencies supported by the provider for this benefit + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun frequencies(): Optional> = frequencies.getOptional("frequencies") /** * Whether the provider supports HSA contribution limits. Empty if this feature is not supported * for the benefit. This array only has values for HSA benefits. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ fun hsaContributionLimit(): Optional> = - Optional.ofNullable(hsaContributionLimit.getNullable("hsa_contribution_limit")) + hsaContributionLimit.getOptional("hsa_contribution_limit") - /** Type of benefit. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) + /** + * Type of benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") - /** Whether the provider supports an annual maximum for this benefit. */ + /** + * Returns the raw JSON value of [annualMaximum]. + * + * Unlike [annualMaximum], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("annual_maximum") @ExcludeMissing fun _annualMaximum(): JsonField = annualMaximum /** - * Whether the provider supports catch up for this benefit. This field will only be true for - * retirement benefits. + * Returns the raw JSON value of [catchUp]. + * + * Unlike [catchUp], this method doesn't throw if the JSON field has an unexpected type. */ @JsonProperty("catch_up") @ExcludeMissing fun _catchUp(): JsonField = catchUp - /** Supported contribution types. An empty array indicates contributions are not supported. */ + /** + * Returns the raw JSON value of [companyContribution]. + * + * Unlike [companyContribution], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("company_contribution") @ExcludeMissing fun _companyContribution(): JsonField> = companyContribution + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description - /** Supported deduction types. An empty array indicates deductions are not supported. */ + /** + * Returns the raw JSON value of [employeeDeduction]. + * + * Unlike [employeeDeduction], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("employee_deduction") @ExcludeMissing fun _employeeDeduction(): JsonField> = employeeDeduction - /** The list of frequencies supported by the provider for this benefit */ + /** + * Returns the raw JSON value of [frequencies]. + * + * Unlike [frequencies], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("frequencies") @ExcludeMissing fun _frequencies(): JsonField> = frequencies /** - * Whether the provider supports HSA contribution limits. Empty if this feature is not supported - * for the benefit. This array only has values for HSA benefits. + * Returns the raw JSON value of [hsaContributionLimit]. + * + * Unlike [hsaContributionLimit], this method doesn't throw if the JSON field has an unexpected + * type. */ @JsonProperty("hsa_contribution_limit") @ExcludeMissing fun _hsaContributionLimit(): JsonField> = hsaContributionLimit - /** Type of benefit. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): SupportedBenefit = apply { - if (validated) { - return@apply - } - - annualMaximum() - catchUp() - companyContribution() - description() - employeeDeduction() - frequencies() - hsaContributionLimit() - type() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [SupportedBenefit]. */ @JvmStatic fun builder() = Builder() } @@ -182,15 +250,24 @@ private constructor( fun annualMaximum(annualMaximum: Boolean?) = annualMaximum(JsonField.ofNullable(annualMaximum)) - /** Whether the provider supports an annual maximum for this benefit. */ + /** + * Alias for [Builder.annualMaximum]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun annualMaximum(annualMaximum: Boolean) = annualMaximum(annualMaximum as Boolean?) - /** Whether the provider supports an annual maximum for this benefit. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 + /** Alias for calling [Builder.annualMaximum] with `annualMaximum.orElse(null)`. */ fun annualMaximum(annualMaximum: Optional) = - annualMaximum(annualMaximum.orElse(null) as Boolean?) + annualMaximum(annualMaximum.getOrNull()) - /** Whether the provider supports an annual maximum for this benefit. */ + /** + * Sets [Builder.annualMaximum] to an arbitrary JSON value. + * + * You should usually call [Builder.annualMaximum] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun annualMaximum(annualMaximum: JsonField) = apply { this.annualMaximum = annualMaximum } @@ -202,21 +279,20 @@ private constructor( fun catchUp(catchUp: Boolean?) = catchUp(JsonField.ofNullable(catchUp)) /** - * Whether the provider supports catch up for this benefit. This field will only be true for - * retirement benefits. + * Alias for [Builder.catchUp]. + * + * This unboxed primitive overload exists for backwards compatibility. */ fun catchUp(catchUp: Boolean) = catchUp(catchUp as Boolean?) - /** - * Whether the provider supports catch up for this benefit. This field will only be true for - * retirement benefits. - */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun catchUp(catchUp: Optional) = catchUp(catchUp.orElse(null) as Boolean?) + /** Alias for calling [Builder.catchUp] with `catchUp.orElse(null)`. */ + fun catchUp(catchUp: Optional) = catchUp(catchUp.getOrNull()) /** - * Whether the provider supports catch up for this benefit. This field will only be true for - * retirement benefits. + * Sets [Builder.catchUp] to an arbitrary JSON value. + * + * You should usually call [Builder.catchUp] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. */ fun catchUp(catchUp: JsonField) = apply { this.catchUp = catchUp } @@ -227,13 +303,17 @@ private constructor( companyContribution(JsonField.ofNullable(companyContribution)) /** - * Supported contribution types. An empty array indicates contributions are not supported. + * Alias for calling [Builder.companyContribution] with `companyContribution.orElse(null)`. */ fun companyContribution(companyContribution: Optional>) = - companyContribution(companyContribution.orElse(null)) + companyContribution(companyContribution.getOrNull()) /** - * Supported contribution types. An empty array indicates contributions are not supported. + * Sets [Builder.companyContribution] to an arbitrary JSON value. + * + * You should usually call [Builder.companyContribution] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. */ fun companyContribution(companyContribution: JsonField>) = apply { @@ -241,51 +321,59 @@ private constructor( } /** - * Supported contribution types. An empty array indicates contributions are not supported. + * Adds a single [CompanyContribution] to [Builder.companyContribution]. + * + * @throws IllegalStateException if the field was previously set to a non-list. */ fun addCompanyContribution(companyContribution: CompanyContribution) = apply { this.companyContribution = - (this.companyContribution ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(companyContribution) + (this.companyContribution ?: JsonField.of(mutableListOf())).also { + checkKnown("companyContribution", it).add(companyContribution) } } fun description(description: String?) = description(JsonField.ofNullable(description)) - fun description(description: Optional) = description(description.orElse(null)) + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun description(description: JsonField) = apply { this.description = description } /** Supported deduction types. An empty array indicates deductions are not supported. */ fun employeeDeduction(employeeDeduction: List?) = employeeDeduction(JsonField.ofNullable(employeeDeduction)) - /** Supported deduction types. An empty array indicates deductions are not supported. */ + /** Alias for calling [Builder.employeeDeduction] with `employeeDeduction.orElse(null)`. */ fun employeeDeduction(employeeDeduction: Optional>) = - employeeDeduction(employeeDeduction.orElse(null)) + employeeDeduction(employeeDeduction.getOrNull()) - /** Supported deduction types. An empty array indicates deductions are not supported. */ + /** + * Sets [Builder.employeeDeduction] to an arbitrary JSON value. + * + * You should usually call [Builder.employeeDeduction] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ fun employeeDeduction(employeeDeduction: JsonField>) = apply { this.employeeDeduction = employeeDeduction.map { it.toMutableList() } } - /** Supported deduction types. An empty array indicates deductions are not supported. */ + /** + * Adds a single [EmployeeDeduction] to [Builder.employeeDeduction]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addEmployeeDeduction(employeeDeduction: EmployeeDeduction) = apply { this.employeeDeduction = - (this.employeeDeduction ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(employeeDeduction) + (this.employeeDeduction ?: JsonField.of(mutableListOf())).also { + checkKnown("employeeDeduction", it).add(employeeDeduction) } } @@ -293,22 +381,26 @@ private constructor( fun frequencies(frequencies: List) = frequencies(JsonField.of(frequencies)) - /** The list of frequencies supported by the provider for this benefit */ + /** + * Sets [Builder.frequencies] to an arbitrary JSON value. + * + * You should usually call [Builder.frequencies] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ fun frequencies(frequencies: JsonField>) = apply { this.frequencies = frequencies.map { it.toMutableList() } } - /** The list of frequencies supported by the provider for this benefit */ + /** + * Adds a single [BenefitFrequency] to [frequencies]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ fun addFrequency(frequency: BenefitFrequency) = apply { frequencies = - (frequencies ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(frequency) + (frequencies ?: JsonField.of(mutableListOf())).also { + checkKnown("frequencies", it).add(frequency) } } @@ -320,15 +412,18 @@ private constructor( hsaContributionLimit(JsonField.ofNullable(hsaContributionLimit)) /** - * Whether the provider supports HSA contribution limits. Empty if this feature is not - * supported for the benefit. This array only has values for HSA benefits. + * Alias for calling [Builder.hsaContributionLimit] with + * `hsaContributionLimit.orElse(null)`. */ fun hsaContributionLimit(hsaContributionLimit: Optional>) = - hsaContributionLimit(hsaContributionLimit.orElse(null)) + hsaContributionLimit(hsaContributionLimit.getOrNull()) /** - * Whether the provider supports HSA contribution limits. Empty if this feature is not - * supported for the benefit. This array only has values for HSA benefits. + * Sets [Builder.hsaContributionLimit] to an arbitrary JSON value. + * + * You should usually call [Builder.hsaContributionLimit] with a well-typed + * `List` value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. */ fun hsaContributionLimit(hsaContributionLimit: JsonField>) = apply { @@ -336,29 +431,30 @@ private constructor( } /** - * Whether the provider supports HSA contribution limits. Empty if this feature is not - * supported for the benefit. This array only has values for HSA benefits. + * Adds a single [HsaContributionLimit] to [Builder.hsaContributionLimit]. + * + * @throws IllegalStateException if the field was previously set to a non-list. */ fun addHsaContributionLimit(hsaContributionLimit: HsaContributionLimit) = apply { this.hsaContributionLimit = - (this.hsaContributionLimit ?: JsonField.of(mutableListOf())).apply { - asKnown() - .orElseThrow { - IllegalStateException( - "Field was set to non-list type: ${javaClass.simpleName}" - ) - } - .add(hsaContributionLimit) + (this.hsaContributionLimit ?: JsonField.of(mutableListOf())).also { + checkKnown("hsaContributionLimit", it).add(hsaContributionLimit) } } /** Type of benefit. */ fun type(type: BenefitType?) = type(JsonField.ofNullable(type)) - /** Type of benefit. */ - fun type(type: Optional) = type(type.orElse(null)) + /** Alias for calling [Builder.type] with `type.orElse(null)`. */ + fun type(type: Optional) = type(type.getOrNull()) - /** Type of benefit. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [BenefitType] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun type(type: JsonField) = apply { this.type = type } fun additionalProperties(additionalProperties: Map) = apply { @@ -380,6 +476,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [SupportedBenefit]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): SupportedBenefit = SupportedBenefit( annualMaximum, @@ -390,10 +491,55 @@ private constructor( (frequencies ?: JsonMissing.of()).map { it.toImmutable() }, (hsaContributionLimit ?: JsonMissing.of()).map { it.toImmutable() }, type, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): SupportedBenefit = apply { + if (validated) { + return@apply + } + + annualMaximum() + catchUp() + companyContribution().ifPresent { it.forEach { it?.validate() } } + description() + employeeDeduction().ifPresent { it.forEach { it?.validate() } } + frequencies().ifPresent { it.forEach { it?.validate() } } + hsaContributionLimit().ifPresent { it.forEach { it?.validate() } } + type().ifPresent { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (annualMaximum.asKnown().isPresent) 1 else 0) + + (if (catchUp.asKnown().isPresent) 1 else 0) + + (companyContribution.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } + ?: 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (employeeDeduction.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } + ?: 0) + + (frequencies.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } ?: 0) + + (hsaContributionLimit.asKnown().getOrNull()?.sumOf { (it?.validity() ?: 0).toInt() } + ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + class CompanyContribution @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -483,6 +629,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): CompanyContribution = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -584,6 +757,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): EmployeeDeduction = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -687,6 +887,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): HsaContributionLimit = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/UnenrolledIndividual.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/UnenrolledIndividual.kt index f5adb2ec..2ced037c 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/UnenrolledIndividual.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/UnenrolledIndividual.kt @@ -10,62 +10,87 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@NoAutoDetect class UnenrolledIndividual -@JsonCreator private constructor( - @JsonProperty("body") @ExcludeMissing private val body: JsonField = JsonMissing.of(), - @JsonProperty("code") @ExcludeMissing private val code: JsonField = JsonMissing.of(), - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val body: JsonField, + private val code: JsonField, + private val individualId: JsonField, + private val additionalProperties: MutableMap, ) { - fun body(): Optional = Optional.ofNullable(body.getNullable("body")) - - /** HTTP status code */ - fun code(): Optional = Optional.ofNullable(code.getNullable("code")) - - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) - + @JsonCreator + private constructor( + @JsonProperty("body") @ExcludeMissing body: JsonField = JsonMissing.of(), + @JsonProperty("code") @ExcludeMissing code: JsonField = JsonMissing.of(), + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of(), + ) : this(body, code, individualId, mutableMapOf()) + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun body(): Optional = body.getOptional("body") + + /** + * HTTP status code + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun code(): Optional = code.getOptional("code") + + /** + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") + + /** + * Returns the raw JSON value of [body]. + * + * Unlike [body], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("body") @ExcludeMissing fun _body(): JsonField = body - /** HTTP status code */ + /** + * Returns the raw JSON value of [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): UnenrolledIndividual = apply { - if (validated) { - return@apply - } - - body().ifPresent { it.validate() } - code() - individualId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [UnenrolledIndividual]. */ @JvmStatic fun builder() = Builder() } @@ -87,16 +112,34 @@ private constructor( fun body(body: Body) = body(JsonField.of(body)) + /** + * Sets [Builder.body] to an arbitrary JSON value. + * + * You should usually call [Builder.body] with a well-typed [Body] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun body(body: JsonField) = apply { this.body = body } /** HTTP status code */ fun code(code: Long) = code(JsonField.of(code)) - /** HTTP status code */ + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun code(code: JsonField) = apply { this.code = code } fun individualId(individualId: String) = individualId(JsonField.of(individualId)) + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -120,66 +163,124 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [UnenrolledIndividual]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): UnenrolledIndividual = - UnenrolledIndividual(body, code, individualId, additionalProperties.toImmutable()) + UnenrolledIndividual(body, code, individualId, additionalProperties.toMutableMap()) } - @NoAutoDetect - class Body - @JsonCreator - private constructor( - @JsonProperty("finch_code") - @ExcludeMissing - private val finchCode: JsonField = JsonMissing.of(), - @JsonProperty("message") - @ExcludeMissing - private val message: JsonField = JsonMissing.of(), - @JsonProperty("name") - @ExcludeMissing - private val name: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), - ) { + private var validated: Boolean = false + + fun validate(): UnenrolledIndividual = apply { + if (validated) { + return@apply + } + + body().ifPresent { it.validate() } + code() + individualId() + validated = true + } - /** A descriptive identifier for the response. */ - fun finchCode(): Optional = Optional.ofNullable(finchCode.getNullable("finch_code")) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } - /** Short description in English that provides more information about the response. */ - fun message(): Optional = Optional.ofNullable(message.getNullable("message")) + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (body.asKnown().getOrNull()?.validity() ?: 0) + + (if (code.asKnown().isPresent) 1 else 0) + + (if (individualId.asKnown().isPresent) 1 else 0) - /** Identifier indicating whether the benefit was newly enrolled or updated. */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + class Body + private constructor( + private val finchCode: JsonField, + private val message: JsonField, + private val name: JsonField, + private val additionalProperties: MutableMap, + ) { - /** A descriptive identifier for the response. */ + @JsonCreator + private constructor( + @JsonProperty("finch_code") + @ExcludeMissing + finchCode: JsonField = JsonMissing.of(), + @JsonProperty("message") @ExcludeMissing message: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + ) : this(finchCode, message, name, mutableMapOf()) + + /** + * A descriptive identifier for the response. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun finchCode(): Optional = finchCode.getOptional("finch_code") + + /** + * Short description in English that provides more information about the response. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun message(): Optional = message.getOptional("message") + + /** + * Identifier indicating whether the benefit was newly enrolled or updated. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = name.getOptional("name") + + /** + * Returns the raw JSON value of [finchCode]. + * + * Unlike [finchCode], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("finch_code") @ExcludeMissing fun _finchCode(): JsonField = finchCode - /** Short description in English that provides more information about the response. */ + /** + * Returns the raw JSON value of [message]. + * + * Unlike [message], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("message") @ExcludeMissing fun _message(): JsonField = message - /** Identifier indicating whether the benefit was newly enrolled or updated. */ + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Body = apply { - if (validated) { - return@apply - } - - finchCode() - message() - name() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Body]. */ @JvmStatic fun builder() = Builder() } @@ -202,28 +303,46 @@ private constructor( /** A descriptive identifier for the response. */ fun finchCode(finchCode: String?) = finchCode(JsonField.ofNullable(finchCode)) - /** A descriptive identifier for the response. */ - fun finchCode(finchCode: Optional) = finchCode(finchCode.orElse(null)) + /** Alias for calling [Builder.finchCode] with `finchCode.orElse(null)`. */ + fun finchCode(finchCode: Optional) = finchCode(finchCode.getOrNull()) - /** A descriptive identifier for the response. */ + /** + * Sets [Builder.finchCode] to an arbitrary JSON value. + * + * You should usually call [Builder.finchCode] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun finchCode(finchCode: JsonField) = apply { this.finchCode = finchCode } /** Short description in English that provides more information about the response. */ fun message(message: String?) = message(JsonField.ofNullable(message)) - /** Short description in English that provides more information about the response. */ - fun message(message: Optional) = message(message.orElse(null)) + /** Alias for calling [Builder.message] with `message.orElse(null)`. */ + fun message(message: Optional) = message(message.getOrNull()) - /** Short description in English that provides more information about the response. */ + /** + * Sets [Builder.message] to an arbitrary JSON value. + * + * You should usually call [Builder.message] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun message(message: JsonField) = apply { this.message = message } /** Identifier indicating whether the benefit was newly enrolled or updated. */ fun name(name: String?) = name(JsonField.ofNullable(name)) - /** Identifier indicating whether the benefit was newly enrolled or updated. */ - fun name(name: Optional) = name(name.orElse(null)) + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - /** Identifier indicating whether the benefit was newly enrolled or updated. */ + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun name(name: JsonField) = apply { this.name = name } fun additionalProperties(additionalProperties: Map) = apply { @@ -245,9 +364,47 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): Body = Body(finchCode, message, name, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [Body]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Body = Body(finchCode, message, name, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + finchCode() + message() + name() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (finchCode.asKnown().isPresent) 1 else 0) + + (if (message.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/UpdateCompanyBenefitResponse.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/UpdateCompanyBenefitResponse.kt index 95463baa..fc71a1bc 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/UpdateCompanyBenefitResponse.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/UpdateCompanyBenefitResponse.kt @@ -10,45 +10,59 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.checkRequired -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable +import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects -@NoAutoDetect class UpdateCompanyBenefitResponse -@JsonCreator private constructor( - @JsonProperty("benefit_id") - @ExcludeMissing - private val benefitId: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val benefitId: JsonField, + private val additionalProperties: MutableMap, ) { + @JsonCreator + private constructor( + @JsonProperty("benefit_id") @ExcludeMissing benefitId: JsonField = JsonMissing.of() + ) : this(benefitId, mutableMapOf()) + + /** + * The id of the benefit. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type or is unexpectedly + * missing or null (e.g. if the server responded with an unexpected value). + */ fun benefitId(): String = benefitId.getRequired("benefit_id") + /** + * Returns the raw JSON value of [benefitId]. + * + * Unlike [benefitId], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("benefit_id") @ExcludeMissing fun _benefitId(): JsonField = benefitId + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): UpdateCompanyBenefitResponse = apply { - if (validated) { - return@apply - } - - benefitId() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [UpdateCompanyBenefitResponse]. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + */ @JvmStatic fun builder() = Builder() } @@ -64,8 +78,16 @@ private constructor( additionalProperties = updateCompanyBenefitResponse.additionalProperties.toMutableMap() } + /** The id of the benefit. */ fun benefitId(benefitId: String) = benefitId(JsonField.of(benefitId)) + /** + * Sets [Builder.benefitId] to an arbitrary JSON value. + * + * You should usually call [Builder.benefitId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ fun benefitId(benefitId: JsonField) = apply { this.benefitId = benefitId } fun additionalProperties(additionalProperties: Map) = apply { @@ -87,13 +109,51 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [UpdateCompanyBenefitResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .benefitId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): UpdateCompanyBenefitResponse = UpdateCompanyBenefitResponse( checkRequired("benefitId", benefitId), - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): UpdateCompanyBenefitResponse = apply { + if (validated) { + return@apply + } + + benefitId() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = (if (benefitId.asKnown().isPresent) 1 else 0) + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/W42005.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/W42005.kt index 4f4b07fe..84e386cd 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/W42005.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/W42005.kt @@ -11,66 +11,91 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** * A 2005 version of the W-4 tax form containing information on an individual's filing status, * dependents, and withholding details. */ -@NoAutoDetect class W42005 -@JsonCreator private constructor( - @JsonProperty("data") @ExcludeMissing private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonProperty("year") @ExcludeMissing private val year: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val year: JsonField, + private val additionalProperties: MutableMap, ) { - /** Detailed information specific to the 2005 W4 form. */ - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) - - /** Specifies the form type, indicating that this document is a 2005 W4 form. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** The tax year this W4 document applies to. */ - fun year(): Optional = Optional.ofNullable(year.getNullable("year")) - - /** Detailed information specific to the 2005 W4 form. */ + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("year") @ExcludeMissing year: JsonField = JsonMissing.of(), + ) : this(data, type, year, mutableMapOf()) + + /** + * Detailed information specific to the 2005 W4 form. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") + + /** + * Specifies the form type, indicating that this document is a 2005 W4 form. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * The tax year this W4 document applies to. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun year(): Optional = year.getOptional("year") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data - /** Specifies the form type, indicating that this document is a 2005 W4 form. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - /** The tax year this W4 document applies to. */ + /** + * Returns the raw JSON value of [year]. + * + * Unlike [year], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("year") @ExcludeMissing fun _year(): JsonField = year + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): W42005 = apply { - if (validated) { - return@apply - } - - data().ifPresent { it.validate() } - type() - year() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [W42005]. */ @JvmStatic fun builder() = Builder() } @@ -93,26 +118,44 @@ private constructor( /** Detailed information specific to the 2005 W4 form. */ fun data(data: Data) = data(JsonField.of(data)) - /** Detailed information specific to the 2005 W4 form. */ + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun data(data: JsonField) = apply { this.data = data } /** Specifies the form type, indicating that this document is a 2005 W4 form. */ fun type(type: Type) = type(JsonField.of(type)) - /** Specifies the form type, indicating that this document is a 2005 W4 form. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } /** The tax year this W4 document applies to. */ fun year(year: Double?) = year(JsonField.ofNullable(year)) - /** The tax year this W4 document applies to. */ + /** + * Alias for [Builder.year]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun year(year: Double) = year(year as Double?) - /** The tax year this W4 document applies to. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun year(year: Optional) = year(year.orElse(null) as Double?) + /** Alias for calling [Builder.year] with `year.orElse(null)`. */ + fun year(year: Optional) = year(year.getOrNull()) - /** The tax year this W4 document applies to. */ + /** + * Sets [Builder.year] to an arbitrary JSON value. + * + * You should usually call [Builder.year] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun year(year: JsonField) = apply { this.year = year } fun additionalProperties(additionalProperties: Map) = apply { @@ -134,101 +177,189 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): W42005 = W42005(data, type, year, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [W42005]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): W42005 = W42005(data, type, year, additionalProperties.toMutableMap()) + } + + private var validated: Boolean = false + + fun validate(): W42005 = apply { + if (validated) { + return@apply + } + + data().ifPresent { it.validate() } + type().ifPresent { it.validate() } + year() + validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (data.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + + (if (year.asKnown().isPresent) 1 else 0) + /** Detailed information specific to the 2005 W4 form. */ - @NoAutoDetect class Data - @JsonCreator private constructor( - @JsonProperty("additional_withholding") - @ExcludeMissing - private val additionalWithholding: JsonField = JsonMissing.of(), - @JsonProperty("exemption") - @ExcludeMissing - private val exemption: JsonField = JsonMissing.of(), - @JsonProperty("filing_status") - @ExcludeMissing - private val filingStatus: JsonField = JsonMissing.of(), - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonProperty("total_number_of_allowances") - @ExcludeMissing - private val totalNumberOfAllowances: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val additionalWithholding: JsonField, + private val exemption: JsonField, + private val filingStatus: JsonField, + private val individualId: JsonField, + private val totalNumberOfAllowances: JsonField, + private val additionalProperties: MutableMap, ) { - /** Additional withholding amount (in cents). */ + @JsonCreator + private constructor( + @JsonProperty("additional_withholding") + @ExcludeMissing + additionalWithholding: JsonField = JsonMissing.of(), + @JsonProperty("exemption") + @ExcludeMissing + exemption: JsonField = JsonMissing.of(), + @JsonProperty("filing_status") + @ExcludeMissing + filingStatus: JsonField = JsonMissing.of(), + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of(), + @JsonProperty("total_number_of_allowances") + @ExcludeMissing + totalNumberOfAllowances: JsonField = JsonMissing.of(), + ) : this( + additionalWithholding, + exemption, + filingStatus, + individualId, + totalNumberOfAllowances, + mutableMapOf(), + ) + + /** + * Additional withholding amount (in cents). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun additionalWithholding(): Optional = - Optional.ofNullable(additionalWithholding.getNullable("additional_withholding")) + additionalWithholding.getOptional("additional_withholding") - /** Indicates exemption status from federal tax withholding. */ - fun exemption(): Optional = - Optional.ofNullable(exemption.getNullable("exemption")) + /** + * Indicates exemption status from federal tax withholding. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun exemption(): Optional = exemption.getOptional("exemption") - /** The individual's filing status for tax purposes. */ - fun filingStatus(): Optional = - Optional.ofNullable(filingStatus.getNullable("filing_status")) + /** + * The individual's filing status for tax purposes. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun filingStatus(): Optional = filingStatus.getOptional("filing_status") - /** The unique identifier for the individual associated with this 2005 W4 form. */ - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) + /** + * The unique identifier for the individual associated with this 2005 W4 form. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") - /** Total number of allowances claimed (in cents). */ + /** + * Total number of allowances claimed (in cents). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun totalNumberOfAllowances(): Optional = - Optional.ofNullable(totalNumberOfAllowances.getNullable("total_number_of_allowances")) + totalNumberOfAllowances.getOptional("total_number_of_allowances") - /** Additional withholding amount (in cents). */ + /** + * Returns the raw JSON value of [additionalWithholding]. + * + * Unlike [additionalWithholding], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("additional_withholding") @ExcludeMissing fun _additionalWithholding(): JsonField = additionalWithholding - /** Indicates exemption status from federal tax withholding. */ + /** + * Returns the raw JSON value of [exemption]. + * + * Unlike [exemption], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("exemption") @ExcludeMissing fun _exemption(): JsonField = exemption - /** The individual's filing status for tax purposes. */ + /** + * Returns the raw JSON value of [filingStatus]. + * + * Unlike [filingStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("filing_status") @ExcludeMissing fun _filingStatus(): JsonField = filingStatus - /** The unique identifier for the individual associated with this 2005 W4 form. */ + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId - /** Total number of allowances claimed (in cents). */ + /** + * Returns the raw JSON value of [totalNumberOfAllowances]. + * + * Unlike [totalNumberOfAllowances], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("total_number_of_allowances") @ExcludeMissing fun _totalNumberOfAllowances(): JsonField = totalNumberOfAllowances + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Data = apply { - if (validated) { - return@apply - } - - additionalWithholding() - exemption() - filingStatus() - individualId() - totalNumberOfAllowances() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Data]. */ @JvmStatic fun builder() = Builder() } @@ -256,16 +387,28 @@ private constructor( fun additionalWithholding(additionalWithholding: Long?) = additionalWithholding(JsonField.ofNullable(additionalWithholding)) - /** Additional withholding amount (in cents). */ + /** + * Alias for [Builder.additionalWithholding]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun additionalWithholding(additionalWithholding: Long) = additionalWithholding(additionalWithholding as Long?) - /** Additional withholding amount (in cents). */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 + /** + * Alias for calling [Builder.additionalWithholding] with + * `additionalWithholding.orElse(null)`. + */ fun additionalWithholding(additionalWithholding: Optional) = - additionalWithholding(additionalWithholding.orElse(null) as Long?) + additionalWithholding(additionalWithholding.getOrNull()) - /** Additional withholding amount (in cents). */ + /** + * Sets [Builder.additionalWithholding] to an arbitrary JSON value. + * + * You should usually call [Builder.additionalWithholding] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun additionalWithholding(additionalWithholding: JsonField) = apply { this.additionalWithholding = additionalWithholding } @@ -273,13 +416,30 @@ private constructor( /** Indicates exemption status from federal tax withholding. */ fun exemption(exemption: Exemption) = exemption(JsonField.of(exemption)) - /** Indicates exemption status from federal tax withholding. */ + /** + * Sets [Builder.exemption] to an arbitrary JSON value. + * + * You should usually call [Builder.exemption] with a well-typed [Exemption] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun exemption(exemption: JsonField) = apply { this.exemption = exemption } /** The individual's filing status for tax purposes. */ - fun filingStatus(filingStatus: FilingStatus) = filingStatus(JsonField.of(filingStatus)) + fun filingStatus(filingStatus: FilingStatus?) = + filingStatus(JsonField.ofNullable(filingStatus)) - /** The individual's filing status for tax purposes. */ + /** Alias for calling [Builder.filingStatus] with `filingStatus.orElse(null)`. */ + fun filingStatus(filingStatus: Optional) = + filingStatus(filingStatus.getOrNull()) + + /** + * Sets [Builder.filingStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.filingStatus] with a well-typed [FilingStatus] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun filingStatus(filingStatus: JsonField) = apply { this.filingStatus = filingStatus } @@ -287,7 +447,13 @@ private constructor( /** The unique identifier for the individual associated with this 2005 W4 form. */ fun individualId(individualId: String) = individualId(JsonField.of(individualId)) - /** The unique identifier for the individual associated with this 2005 W4 form. */ + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -296,16 +462,28 @@ private constructor( fun totalNumberOfAllowances(totalNumberOfAllowances: Long?) = totalNumberOfAllowances(JsonField.ofNullable(totalNumberOfAllowances)) - /** Total number of allowances claimed (in cents). */ + /** + * Alias for [Builder.totalNumberOfAllowances]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun totalNumberOfAllowances(totalNumberOfAllowances: Long) = totalNumberOfAllowances(totalNumberOfAllowances as Long?) - /** Total number of allowances claimed (in cents). */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 + /** + * Alias for calling [Builder.totalNumberOfAllowances] with + * `totalNumberOfAllowances.orElse(null)`. + */ fun totalNumberOfAllowances(totalNumberOfAllowances: Optional) = - totalNumberOfAllowances(totalNumberOfAllowances.orElse(null) as Long?) + totalNumberOfAllowances(totalNumberOfAllowances.getOrNull()) - /** Total number of allowances claimed (in cents). */ + /** + * Sets [Builder.totalNumberOfAllowances] to an arbitrary JSON value. + * + * You should usually call [Builder.totalNumberOfAllowances] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun totalNumberOfAllowances(totalNumberOfAllowances: JsonField) = apply { this.totalNumberOfAllowances = totalNumberOfAllowances } @@ -329,6 +507,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Data = Data( additionalWithholding, @@ -336,10 +519,47 @@ private constructor( filingStatus, individualId, totalNumberOfAllowances, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + additionalWithholding() + exemption().ifPresent { it.validate() } + filingStatus().ifPresent { it.validate() } + individualId() + totalNumberOfAllowances() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (additionalWithholding.asKnown().isPresent) 1 else 0) + + (exemption.asKnown().getOrNull()?.validity() ?: 0) + + (filingStatus.asKnown().getOrNull()?.validity() ?: 0) + + (if (individualId.asKnown().isPresent) 1 else 0) + + (if (totalNumberOfAllowances.asKnown().isPresent) 1 else 0) + /** Indicates exemption status from federal tax withholding. */ class Exemption @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -432,6 +652,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Exemption = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -547,6 +794,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): FilingStatus = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -657,6 +931,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/W42020.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/W42020.kt index 42baad1c..b6eeffd2 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/W42020.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/W42020.kt @@ -11,66 +11,91 @@ import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue -import com.tryfinch.api.core.NoAutoDetect -import com.tryfinch.api.core.immutableEmptyMap -import com.tryfinch.api.core.toImmutable import com.tryfinch.api.errors.FinchInvalidDataException +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull /** * A 2020 version of the W-4 tax form containing information on an individual's filing status, * dependents, and withholding details. */ -@NoAutoDetect class W42020 -@JsonCreator private constructor( - @JsonProperty("data") @ExcludeMissing private val data: JsonField = JsonMissing.of(), - @JsonProperty("type") @ExcludeMissing private val type: JsonField = JsonMissing.of(), - @JsonProperty("year") @ExcludeMissing private val year: JsonField = JsonMissing.of(), - @JsonAnySetter private val additionalProperties: Map = immutableEmptyMap(), + private val data: JsonField, + private val type: JsonField, + private val year: JsonField, + private val additionalProperties: MutableMap, ) { - /** Detailed information specific to the 2020 W4 form. */ - fun data(): Optional = Optional.ofNullable(data.getNullable("data")) - - /** Specifies the form type, indicating that this document is a 2020 W4 form. */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** The tax year this W4 document applies to. */ - fun year(): Optional = Optional.ofNullable(year.getNullable("year")) - - /** Detailed information specific to the 2020 W4 form. */ + @JsonCreator + private constructor( + @JsonProperty("data") @ExcludeMissing data: JsonField = JsonMissing.of(), + @JsonProperty("type") @ExcludeMissing type: JsonField = JsonMissing.of(), + @JsonProperty("year") @ExcludeMissing year: JsonField = JsonMissing.of(), + ) : this(data, type, year, mutableMapOf()) + + /** + * Detailed information specific to the 2020 W4 form. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun data(): Optional = data.getOptional("data") + + /** + * Specifies the form type, indicating that this document is a 2020 W4 form. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = type.getOptional("type") + + /** + * The tax year this W4 document applies to. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun year(): Optional = year.getOptional("year") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data - /** Specifies the form type, indicating that this document is a 2020 W4 form. */ + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type - /** The tax year this W4 document applies to. */ + /** + * Returns the raw JSON value of [year]. + * + * Unlike [year], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("year") @ExcludeMissing fun _year(): JsonField = year + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): W42020 = apply { - if (validated) { - return@apply - } - - data().ifPresent { it.validate() } - type() - year() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [W42020]. */ @JvmStatic fun builder() = Builder() } @@ -93,26 +118,44 @@ private constructor( /** Detailed information specific to the 2020 W4 form. */ fun data(data: Data) = data(JsonField.of(data)) - /** Detailed information specific to the 2020 W4 form. */ + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed [Data] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun data(data: JsonField) = apply { this.data = data } /** Specifies the form type, indicating that this document is a 2020 W4 form. */ fun type(type: Type) = type(JsonField.of(type)) - /** Specifies the form type, indicating that this document is a 2020 W4 form. */ + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun type(type: JsonField) = apply { this.type = type } /** The tax year this W4 document applies to. */ fun year(year: Double?) = year(JsonField.ofNullable(year)) - /** The tax year this W4 document applies to. */ + /** + * Alias for [Builder.year]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun year(year: Double) = year(year as Double?) - /** The tax year this W4 document applies to. */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun year(year: Optional) = year(year.orElse(null) as Double?) + /** Alias for calling [Builder.year] with `year.orElse(null)`. */ + fun year(year: Optional) = year(year.getOrNull()) - /** The tax year this W4 document applies to. */ + /** + * Sets [Builder.year] to an arbitrary JSON value. + * + * You should usually call [Builder.year] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun year(year: JsonField) = apply { this.year = year } fun additionalProperties(additionalProperties: Map) = apply { @@ -134,147 +177,262 @@ private constructor( keys.forEach(::removeAdditionalProperty) } - fun build(): W42020 = W42020(data, type, year, additionalProperties.toImmutable()) + /** + * Returns an immutable instance of [W42020]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): W42020 = W42020(data, type, year, additionalProperties.toMutableMap()) } + private var validated: Boolean = false + + fun validate(): W42020 = apply { + if (validated) { + return@apply + } + + data().ifPresent { it.validate() } + type().ifPresent { it.validate() } + year() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (data.asKnown().getOrNull()?.validity() ?: 0) + + (type.asKnown().getOrNull()?.validity() ?: 0) + + (if (year.asKnown().isPresent) 1 else 0) + /** Detailed information specific to the 2020 W4 form. */ - @NoAutoDetect class Data - @JsonCreator private constructor( - @JsonProperty("amount_for_other_dependents") - @ExcludeMissing - private val amountForOtherDependents: JsonField = JsonMissing.of(), - @JsonProperty("amount_for_qualifying_children_under_17") - @ExcludeMissing - private val amountForQualifyingChildrenUnder17: JsonField = JsonMissing.of(), - @JsonProperty("deductions") - @ExcludeMissing - private val deductions: JsonField = JsonMissing.of(), - @JsonProperty("extra_withholding") - @ExcludeMissing - private val extraWithholding: JsonField = JsonMissing.of(), - @JsonProperty("filing_status") - @ExcludeMissing - private val filingStatus: JsonField = JsonMissing.of(), - @JsonProperty("individual_id") - @ExcludeMissing - private val individualId: JsonField = JsonMissing.of(), - @JsonProperty("other_income") - @ExcludeMissing - private val otherIncome: JsonField = JsonMissing.of(), - @JsonProperty("total_claim_dependent_and_other_credits") - @ExcludeMissing - private val totalClaimDependentAndOtherCredits: JsonField = JsonMissing.of(), - @JsonAnySetter - private val additionalProperties: Map = immutableEmptyMap(), + private val amountForOtherDependents: JsonField, + private val amountForQualifyingChildrenUnder17: JsonField, + private val deductions: JsonField, + private val extraWithholding: JsonField, + private val filingStatus: JsonField, + private val individualId: JsonField, + private val otherIncome: JsonField, + private val totalClaimDependentAndOtherCredits: JsonField, + private val additionalProperties: MutableMap, ) { - /** Amount claimed for dependents other than qualifying children under 17 (in cents). */ + @JsonCreator + private constructor( + @JsonProperty("amount_for_other_dependents") + @ExcludeMissing + amountForOtherDependents: JsonField = JsonMissing.of(), + @JsonProperty("amount_for_qualifying_children_under_17") + @ExcludeMissing + amountForQualifyingChildrenUnder17: JsonField = JsonMissing.of(), + @JsonProperty("deductions") + @ExcludeMissing + deductions: JsonField = JsonMissing.of(), + @JsonProperty("extra_withholding") + @ExcludeMissing + extraWithholding: JsonField = JsonMissing.of(), + @JsonProperty("filing_status") + @ExcludeMissing + filingStatus: JsonField = JsonMissing.of(), + @JsonProperty("individual_id") + @ExcludeMissing + individualId: JsonField = JsonMissing.of(), + @JsonProperty("other_income") + @ExcludeMissing + otherIncome: JsonField = JsonMissing.of(), + @JsonProperty("total_claim_dependent_and_other_credits") + @ExcludeMissing + totalClaimDependentAndOtherCredits: JsonField = JsonMissing.of(), + ) : this( + amountForOtherDependents, + amountForQualifyingChildrenUnder17, + deductions, + extraWithholding, + filingStatus, + individualId, + otherIncome, + totalClaimDependentAndOtherCredits, + mutableMapOf(), + ) + + /** + * Amount claimed for dependents other than qualifying children under 17 (in cents). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun amountForOtherDependents(): Optional = - Optional.ofNullable(amountForOtherDependents.getNullable("amount_for_other_dependents")) + amountForOtherDependents.getOptional("amount_for_other_dependents") - /** Amount claimed for dependents under 17 years old (in cents). */ + /** + * Amount claimed for dependents under 17 years old (in cents). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun amountForQualifyingChildrenUnder17(): Optional = - Optional.ofNullable( - amountForQualifyingChildrenUnder17.getNullable( - "amount_for_qualifying_children_under_17" - ) + amountForQualifyingChildrenUnder17.getOptional( + "amount_for_qualifying_children_under_17" ) - /** Deductible expenses (in cents). */ - fun deductions(): Optional = Optional.ofNullable(deductions.getNullable("deductions")) + /** + * Deductible expenses (in cents). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun deductions(): Optional = deductions.getOptional("deductions") - /** Additional withholding amount (in cents). */ - fun extraWithholding(): Optional = - Optional.ofNullable(extraWithholding.getNullable("extra_withholding")) + /** + * Additional withholding amount (in cents). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun extraWithholding(): Optional = extraWithholding.getOptional("extra_withholding") - /** The individual's filing status for tax purposes. */ - fun filingStatus(): Optional = - Optional.ofNullable(filingStatus.getNullable("filing_status")) + /** + * The individual's filing status for tax purposes. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun filingStatus(): Optional = filingStatus.getOptional("filing_status") - /** The unique identifier for the individual associated with this document. */ - fun individualId(): Optional = - Optional.ofNullable(individualId.getNullable("individual_id")) + /** + * The unique identifier for the individual associated with this document. + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun individualId(): Optional = individualId.getOptional("individual_id") - /** Additional income from sources outside of primary employment (in cents). */ - fun otherIncome(): Optional = - Optional.ofNullable(otherIncome.getNullable("other_income")) + /** + * Additional income from sources outside of primary employment (in cents). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun otherIncome(): Optional = otherIncome.getOptional("other_income") - /** Total amount claimed for dependents and other credits (in cents). */ + /** + * Total amount claimed for dependents and other credits (in cents). + * + * @throws FinchInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ fun totalClaimDependentAndOtherCredits(): Optional = - Optional.ofNullable( - totalClaimDependentAndOtherCredits.getNullable( - "total_claim_dependent_and_other_credits" - ) + totalClaimDependentAndOtherCredits.getOptional( + "total_claim_dependent_and_other_credits" ) - /** Amount claimed for dependents other than qualifying children under 17 (in cents). */ + /** + * Returns the raw JSON value of [amountForOtherDependents]. + * + * Unlike [amountForOtherDependents], this method doesn't throw if the JSON field has an + * unexpected type. + */ @JsonProperty("amount_for_other_dependents") @ExcludeMissing fun _amountForOtherDependents(): JsonField = amountForOtherDependents - /** Amount claimed for dependents under 17 years old (in cents). */ + /** + * Returns the raw JSON value of [amountForQualifyingChildrenUnder17]. + * + * Unlike [amountForQualifyingChildrenUnder17], this method doesn't throw if the JSON field + * has an unexpected type. + */ @JsonProperty("amount_for_qualifying_children_under_17") @ExcludeMissing fun _amountForQualifyingChildrenUnder17(): JsonField = amountForQualifyingChildrenUnder17 - /** Deductible expenses (in cents). */ + /** + * Returns the raw JSON value of [deductions]. + * + * Unlike [deductions], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("deductions") @ExcludeMissing fun _deductions(): JsonField = deductions - /** Additional withholding amount (in cents). */ + /** + * Returns the raw JSON value of [extraWithholding]. + * + * Unlike [extraWithholding], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("extra_withholding") @ExcludeMissing fun _extraWithholding(): JsonField = extraWithholding - /** The individual's filing status for tax purposes. */ + /** + * Returns the raw JSON value of [filingStatus]. + * + * Unlike [filingStatus], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("filing_status") @ExcludeMissing fun _filingStatus(): JsonField = filingStatus - /** The unique identifier for the individual associated with this document. */ + /** + * Returns the raw JSON value of [individualId]. + * + * Unlike [individualId], this method doesn't throw if the JSON field has an unexpected + * type. + */ @JsonProperty("individual_id") @ExcludeMissing fun _individualId(): JsonField = individualId - /** Additional income from sources outside of primary employment (in cents). */ + /** + * Returns the raw JSON value of [otherIncome]. + * + * Unlike [otherIncome], this method doesn't throw if the JSON field has an unexpected type. + */ @JsonProperty("other_income") @ExcludeMissing fun _otherIncome(): JsonField = otherIncome - /** Total amount claimed for dependents and other credits (in cents). */ + /** + * Returns the raw JSON value of [totalClaimDependentAndOtherCredits]. + * + * Unlike [totalClaimDependentAndOtherCredits], this method doesn't throw if the JSON field + * has an unexpected type. + */ @JsonProperty("total_claim_dependent_and_other_credits") @ExcludeMissing fun _totalClaimDependentAndOtherCredits(): JsonField = totalClaimDependentAndOtherCredits + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - private var validated: Boolean = false - - fun validate(): Data = apply { - if (validated) { - return@apply - } - - amountForOtherDependents() - amountForQualifyingChildrenUnder17() - deductions() - extraWithholding() - filingStatus() - individualId() - otherIncome() - totalClaimDependentAndOtherCredits() - validated = true - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Data]. */ @JvmStatic fun builder() = Builder() } @@ -308,16 +466,28 @@ private constructor( fun amountForOtherDependents(amountForOtherDependents: Long?) = amountForOtherDependents(JsonField.ofNullable(amountForOtherDependents)) - /** Amount claimed for dependents other than qualifying children under 17 (in cents). */ + /** + * Alias for [Builder.amountForOtherDependents]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun amountForOtherDependents(amountForOtherDependents: Long) = amountForOtherDependents(amountForOtherDependents as Long?) - /** Amount claimed for dependents other than qualifying children under 17 (in cents). */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 + /** + * Alias for calling [Builder.amountForOtherDependents] with + * `amountForOtherDependents.orElse(null)`. + */ fun amountForOtherDependents(amountForOtherDependents: Optional) = - amountForOtherDependents(amountForOtherDependents.orElse(null) as Long?) + amountForOtherDependents(amountForOtherDependents.getOrNull()) - /** Amount claimed for dependents other than qualifying children under 17 (in cents). */ + /** + * Sets [Builder.amountForOtherDependents] to an arbitrary JSON value. + * + * You should usually call [Builder.amountForOtherDependents] with a well-typed [Long] + * value instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ fun amountForOtherDependents(amountForOtherDependents: JsonField) = apply { this.amountForOtherDependents = amountForOtherDependents } @@ -328,20 +498,29 @@ private constructor( JsonField.ofNullable(amountForQualifyingChildrenUnder17) ) - /** Amount claimed for dependents under 17 years old (in cents). */ + /** + * Alias for [Builder.amountForQualifyingChildrenUnder17]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun amountForQualifyingChildrenUnder17(amountForQualifyingChildrenUnder17: Long) = amountForQualifyingChildrenUnder17(amountForQualifyingChildrenUnder17 as Long?) - /** Amount claimed for dependents under 17 years old (in cents). */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 + /** + * Alias for calling [Builder.amountForQualifyingChildrenUnder17] with + * `amountForQualifyingChildrenUnder17.orElse(null)`. + */ fun amountForQualifyingChildrenUnder17( amountForQualifyingChildrenUnder17: Optional - ) = - amountForQualifyingChildrenUnder17( - amountForQualifyingChildrenUnder17.orElse(null) as Long? - ) + ) = amountForQualifyingChildrenUnder17(amountForQualifyingChildrenUnder17.getOrNull()) - /** Amount claimed for dependents under 17 years old (in cents). */ + /** + * Sets [Builder.amountForQualifyingChildrenUnder17] to an arbitrary JSON value. + * + * You should usually call [Builder.amountForQualifyingChildrenUnder17] with a + * well-typed [Long] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun amountForQualifyingChildrenUnder17( amountForQualifyingChildrenUnder17: JsonField ) = apply { @@ -351,31 +530,50 @@ private constructor( /** Deductible expenses (in cents). */ fun deductions(deductions: Long?) = deductions(JsonField.ofNullable(deductions)) - /** Deductible expenses (in cents). */ + /** + * Alias for [Builder.deductions]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun deductions(deductions: Long) = deductions(deductions as Long?) - /** Deductible expenses (in cents). */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun deductions(deductions: Optional) = - deductions(deductions.orElse(null) as Long?) + /** Alias for calling [Builder.deductions] with `deductions.orElse(null)`. */ + fun deductions(deductions: Optional) = deductions(deductions.getOrNull()) - /** Deductible expenses (in cents). */ + /** + * Sets [Builder.deductions] to an arbitrary JSON value. + * + * You should usually call [Builder.deductions] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun deductions(deductions: JsonField) = apply { this.deductions = deductions } /** Additional withholding amount (in cents). */ fun extraWithholding(extraWithholding: Long?) = extraWithholding(JsonField.ofNullable(extraWithholding)) - /** Additional withholding amount (in cents). */ + /** + * Alias for [Builder.extraWithholding]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun extraWithholding(extraWithholding: Long) = extraWithholding(extraWithholding as Long?) - /** Additional withholding amount (in cents). */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 + /** + * Alias for calling [Builder.extraWithholding] with `extraWithholding.orElse(null)`. + */ fun extraWithholding(extraWithholding: Optional) = - extraWithholding(extraWithholding.orElse(null) as Long?) + extraWithholding(extraWithholding.getOrNull()) - /** Additional withholding amount (in cents). */ + /** + * Sets [Builder.extraWithholding] to an arbitrary JSON value. + * + * You should usually call [Builder.extraWithholding] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun extraWithholding(extraWithholding: JsonField) = apply { this.extraWithholding = extraWithholding } @@ -384,11 +582,17 @@ private constructor( fun filingStatus(filingStatus: FilingStatus?) = filingStatus(JsonField.ofNullable(filingStatus)) - /** The individual's filing status for tax purposes. */ + /** Alias for calling [Builder.filingStatus] with `filingStatus.orElse(null)`. */ fun filingStatus(filingStatus: Optional) = - filingStatus(filingStatus.orElse(null)) + filingStatus(filingStatus.getOrNull()) - /** The individual's filing status for tax purposes. */ + /** + * Sets [Builder.filingStatus] to an arbitrary JSON value. + * + * You should usually call [Builder.filingStatus] with a well-typed [FilingStatus] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun filingStatus(filingStatus: JsonField) = apply { this.filingStatus = filingStatus } @@ -396,7 +600,13 @@ private constructor( /** The unique identifier for the individual associated with this document. */ fun individualId(individualId: String) = individualId(JsonField.of(individualId)) - /** The unique identifier for the individual associated with this document. */ + /** + * Sets [Builder.individualId] to an arbitrary JSON value. + * + * You should usually call [Builder.individualId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun individualId(individualId: JsonField) = apply { this.individualId = individualId } @@ -404,15 +614,23 @@ private constructor( /** Additional income from sources outside of primary employment (in cents). */ fun otherIncome(otherIncome: Long?) = otherIncome(JsonField.ofNullable(otherIncome)) - /** Additional income from sources outside of primary employment (in cents). */ + /** + * Alias for [Builder.otherIncome]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun otherIncome(otherIncome: Long) = otherIncome(otherIncome as Long?) - /** Additional income from sources outside of primary employment (in cents). */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 - fun otherIncome(otherIncome: Optional) = - otherIncome(otherIncome.orElse(null) as Long?) + /** Alias for calling [Builder.otherIncome] with `otherIncome.orElse(null)`. */ + fun otherIncome(otherIncome: Optional) = otherIncome(otherIncome.getOrNull()) - /** Additional income from sources outside of primary employment (in cents). */ + /** + * Sets [Builder.otherIncome] to an arbitrary JSON value. + * + * You should usually call [Builder.otherIncome] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun otherIncome(otherIncome: JsonField) = apply { this.otherIncome = otherIncome } /** Total amount claimed for dependents and other credits (in cents). */ @@ -421,20 +639,29 @@ private constructor( JsonField.ofNullable(totalClaimDependentAndOtherCredits) ) - /** Total amount claimed for dependents and other credits (in cents). */ + /** + * Alias for [Builder.totalClaimDependentAndOtherCredits]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ fun totalClaimDependentAndOtherCredits(totalClaimDependentAndOtherCredits: Long) = totalClaimDependentAndOtherCredits(totalClaimDependentAndOtherCredits as Long?) - /** Total amount claimed for dependents and other credits (in cents). */ - @Suppress("USELESS_CAST") // See https://youtrack.jetbrains.com/issue/KT-74228 + /** + * Alias for calling [Builder.totalClaimDependentAndOtherCredits] with + * `totalClaimDependentAndOtherCredits.orElse(null)`. + */ fun totalClaimDependentAndOtherCredits( totalClaimDependentAndOtherCredits: Optional - ) = - totalClaimDependentAndOtherCredits( - totalClaimDependentAndOtherCredits.orElse(null) as Long? - ) + ) = totalClaimDependentAndOtherCredits(totalClaimDependentAndOtherCredits.getOrNull()) - /** Total amount claimed for dependents and other credits (in cents). */ + /** + * Sets [Builder.totalClaimDependentAndOtherCredits] to an arbitrary JSON value. + * + * You should usually call [Builder.totalClaimDependentAndOtherCredits] with a + * well-typed [Long] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ fun totalClaimDependentAndOtherCredits( totalClaimDependentAndOtherCredits: JsonField ) = apply { @@ -460,6 +687,11 @@ private constructor( keys.forEach(::removeAdditionalProperty) } + /** + * Returns an immutable instance of [Data]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): Data = Data( amountForOtherDependents, @@ -470,10 +702,53 @@ private constructor( individualId, otherIncome, totalClaimDependentAndOtherCredits, - additionalProperties.toImmutable(), + additionalProperties.toMutableMap(), ) } + private var validated: Boolean = false + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + amountForOtherDependents() + amountForQualifyingChildrenUnder17() + deductions() + extraWithholding() + filingStatus().ifPresent { it.validate() } + individualId() + otherIncome() + totalClaimDependentAndOtherCredits() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (amountForOtherDependents.asKnown().isPresent) 1 else 0) + + (if (amountForQualifyingChildrenUnder17.asKnown().isPresent) 1 else 0) + + (if (deductions.asKnown().isPresent) 1 else 0) + + (if (extraWithholding.asKnown().isPresent) 1 else 0) + + (filingStatus.asKnown().getOrNull()?.validity() ?: 0) + + (if (individualId.asKnown().isPresent) 1 else 0) + + (if (otherIncome.asKnown().isPresent) 1 else 0) + + (if (totalClaimDependentAndOtherCredits.asKnown().isPresent) 1 else 0) + /** The individual's filing status for tax purposes. */ class FilingStatus @JsonCreator private constructor(private val value: JsonField) : Enum { @@ -577,6 +852,33 @@ private constructor( FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): FilingStatus = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true @@ -687,6 +989,33 @@ private constructor( fun asString(): String = _value().asString().orElseThrow { FinchInvalidDataException("Value is not a String") } + private var validated: Boolean = false + + fun validate(): Type = apply { + if (validated) { + return@apply + } + + known() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1 + override fun equals(other: Any?): Boolean { if (this === other) { return true diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/WebhookEvent.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/WebhookEvent.kt index fd604b72..43d8873e 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/models/WebhookEvent.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/models/WebhookEvent.kt @@ -12,6 +12,7 @@ import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import com.tryfinch.api.core.BaseDeserializer import com.tryfinch.api.core.BaseSerializer import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.allMaxBy import com.tryfinch.api.core.getOrThrow import com.tryfinch.api.errors.FinchInvalidDataException import java.util.Objects @@ -21,9 +22,9 @@ import java.util.Optional @JsonSerialize(using = WebhookEvent.Serializer::class) class WebhookEvent private constructor( - private val accountUpdate: AccountUpdateEvent? = null, + private val accountUpdated: AccountUpdateEvent? = null, private val jobCompletion: JobCompletionEvent? = null, - private val company: CompanyEvent? = null, + private val companyUpdated: CompanyEvent? = null, private val directory: DirectoryEvent? = null, private val employment: EmploymentEvent? = null, private val individual: IndividualEvent? = null, @@ -32,11 +33,11 @@ private constructor( private val _json: JsonValue? = null, ) { - fun accountUpdate(): Optional = Optional.ofNullable(accountUpdate) + fun accountUpdated(): Optional = Optional.ofNullable(accountUpdated) fun jobCompletion(): Optional = Optional.ofNullable(jobCompletion) - fun company(): Optional = Optional.ofNullable(company) + fun companyUpdated(): Optional = Optional.ofNullable(companyUpdated) fun directory(): Optional = Optional.ofNullable(directory) @@ -48,11 +49,11 @@ private constructor( fun payStatement(): Optional = Optional.ofNullable(payStatement) - fun isAccountUpdate(): Boolean = accountUpdate != null + fun isAccountUpdated(): Boolean = accountUpdated != null fun isJobCompletion(): Boolean = jobCompletion != null - fun isCompany(): Boolean = company != null + fun isCompanyUpdated(): Boolean = companyUpdated != null fun isDirectory(): Boolean = directory != null @@ -64,11 +65,11 @@ private constructor( fun isPayStatement(): Boolean = payStatement != null - fun asAccountUpdate(): AccountUpdateEvent = accountUpdate.getOrThrow("accountUpdate") + fun asAccountUpdated(): AccountUpdateEvent = accountUpdated.getOrThrow("accountUpdated") fun asJobCompletion(): JobCompletionEvent = jobCompletion.getOrThrow("jobCompletion") - fun asCompany(): CompanyEvent = company.getOrThrow("company") + fun asCompanyUpdated(): CompanyEvent = companyUpdated.getOrThrow("companyUpdated") fun asDirectory(): DirectoryEvent = directory.getOrThrow("directory") @@ -82,11 +83,11 @@ private constructor( fun _json(): Optional = Optional.ofNullable(_json) - fun accept(visitor: Visitor): T { - return when { - accountUpdate != null -> visitor.visitAccountUpdate(accountUpdate) + fun accept(visitor: Visitor): T = + when { + accountUpdated != null -> visitor.visitAccountUpdated(accountUpdated) jobCompletion != null -> visitor.visitJobCompletion(jobCompletion) - company != null -> visitor.visitCompany(company) + companyUpdated != null -> visitor.visitCompanyUpdated(companyUpdated) directory != null -> visitor.visitDirectory(directory) employment != null -> visitor.visitEmployment(employment) individual != null -> visitor.visitIndividual(individual) @@ -94,7 +95,6 @@ private constructor( payStatement != null -> visitor.visitPayStatement(payStatement) else -> visitor.unknown(_json) } - } private var validated: Boolean = false @@ -105,16 +105,16 @@ private constructor( accept( object : Visitor { - override fun visitAccountUpdate(accountUpdate: AccountUpdateEvent) { - accountUpdate.validate() + override fun visitAccountUpdated(accountUpdated: AccountUpdateEvent) { + accountUpdated.validate() } override fun visitJobCompletion(jobCompletion: JobCompletionEvent) { jobCompletion.validate() } - override fun visitCompany(company: CompanyEvent) { - company.validate() + override fun visitCompanyUpdated(companyUpdated: CompanyEvent) { + companyUpdated.validate() } override fun visitDirectory(directory: DirectoryEvent) { @@ -141,21 +141,62 @@ private constructor( validated = true } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: FinchInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + accept( + object : Visitor { + override fun visitAccountUpdated(accountUpdated: AccountUpdateEvent) = + accountUpdated.validity() + + override fun visitJobCompletion(jobCompletion: JobCompletionEvent) = + jobCompletion.validity() + + override fun visitCompanyUpdated(companyUpdated: CompanyEvent) = + companyUpdated.validity() + + override fun visitDirectory(directory: DirectoryEvent) = directory.validity() + + override fun visitEmployment(employment: EmploymentEvent) = employment.validity() + + override fun visitIndividual(individual: IndividualEvent) = individual.validity() + + override fun visitPayment(payment: PaymentEvent) = payment.validity() + + override fun visitPayStatement(payStatement: PayStatementEvent) = + payStatement.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + override fun equals(other: Any?): Boolean { if (this === other) { return true } - return /* spotless:off */ other is WebhookEvent && accountUpdate == other.accountUpdate && jobCompletion == other.jobCompletion && company == other.company && directory == other.directory && employment == other.employment && individual == other.individual && payment == other.payment && payStatement == other.payStatement /* spotless:on */ + return /* spotless:off */ other is WebhookEvent && accountUpdated == other.accountUpdated && jobCompletion == other.jobCompletion && companyUpdated == other.companyUpdated && directory == other.directory && employment == other.employment && individual == other.individual && payment == other.payment && payStatement == other.payStatement /* spotless:on */ } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(accountUpdate, jobCompletion, company, directory, employment, individual, payment, payStatement) /* spotless:on */ + override fun hashCode(): Int = /* spotless:off */ Objects.hash(accountUpdated, jobCompletion, companyUpdated, directory, employment, individual, payment, payStatement) /* spotless:on */ override fun toString(): String = when { - accountUpdate != null -> "WebhookEvent{accountUpdate=$accountUpdate}" + accountUpdated != null -> "WebhookEvent{accountUpdated=$accountUpdated}" jobCompletion != null -> "WebhookEvent{jobCompletion=$jobCompletion}" - company != null -> "WebhookEvent{company=$company}" + companyUpdated != null -> "WebhookEvent{companyUpdated=$companyUpdated}" directory != null -> "WebhookEvent{directory=$directory}" employment != null -> "WebhookEvent{employment=$employment}" individual != null -> "WebhookEvent{individual=$individual}" @@ -168,14 +209,16 @@ private constructor( companion object { @JvmStatic - fun ofAccountUpdate(accountUpdate: AccountUpdateEvent) = - WebhookEvent(accountUpdate = accountUpdate) + fun ofAccountUpdated(accountUpdated: AccountUpdateEvent) = + WebhookEvent(accountUpdated = accountUpdated) @JvmStatic fun ofJobCompletion(jobCompletion: JobCompletionEvent) = WebhookEvent(jobCompletion = jobCompletion) - @JvmStatic fun ofCompany(company: CompanyEvent) = WebhookEvent(company = company) + @JvmStatic + fun ofCompanyUpdated(companyUpdated: CompanyEvent) = + WebhookEvent(companyUpdated = companyUpdated) @JvmStatic fun ofDirectory(directory: DirectoryEvent) = WebhookEvent(directory = directory) @@ -197,11 +240,11 @@ private constructor( */ interface Visitor { - fun visitAccountUpdate(accountUpdate: AccountUpdateEvent): T + fun visitAccountUpdated(accountUpdated: AccountUpdateEvent): T fun visitJobCompletion(jobCompletion: JobCompletionEvent): T - fun visitCompany(company: CompanyEvent): T + fun visitCompanyUpdated(companyUpdated: CompanyEvent): T fun visitDirectory(directory: DirectoryEvent): T @@ -232,40 +275,45 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): WebhookEvent { val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return WebhookEvent(accountUpdate = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return WebhookEvent(jobCompletion = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return WebhookEvent(company = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return WebhookEvent(directory = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return WebhookEvent(employment = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return WebhookEvent(individual = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return WebhookEvent(payment = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return WebhookEvent(payStatement = it, _json = json) - } - - return WebhookEvent(_json = json) + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + WebhookEvent(accountUpdated = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + WebhookEvent(jobCompletion = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + WebhookEvent(companyUpdated = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + WebhookEvent(directory = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + WebhookEvent(employment = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + WebhookEvent(individual = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + WebhookEvent(payment = it, _json = json) + }, + tryDeserialize(node, jacksonTypeRef())?.let { + WebhookEvent(payStatement = it, _json = json) + }, + ) + .filterNotNull() + .allMaxBy { it.validity() } + .toList() + return when (bestMatches.size) { + // This can happen if what we're deserializing is completely incompatible with all + // the possible variants (e.g. deserializing from boolean). + 0 -> WebhookEvent(_json = json) + 1 -> bestMatches.single() + // If there's more than one match with the highest validity, then use the first + // completely valid match, or simply the first match if none are completely valid. + else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first() + } } } @@ -277,9 +325,9 @@ private constructor( provider: SerializerProvider, ) { when { - value.accountUpdate != null -> generator.writeObject(value.accountUpdate) + value.accountUpdated != null -> generator.writeObject(value.accountUpdated) value.jobCompletion != null -> generator.writeObject(value.jobCompletion) - value.company != null -> generator.writeObject(value.company) + value.companyUpdated != null -> generator.writeObject(value.companyUpdated) value.directory != null -> generator.writeObject(value.directory) value.employment != null -> generator.writeObject(value.employment) value.individual != null -> generator.writeObject(value.individual) diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccessTokenServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccessTokenServiceAsync.kt index 42797f29..7dd0db87 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccessTokenServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccessTokenServiceAsync.kt @@ -1,20 +1,52 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.AccessTokenCreateParams import com.tryfinch.api.models.CreateAccessTokenResponse import java.util.concurrent.CompletableFuture interface AccessTokenServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Exchange the authorization code for an access token */ - @JvmOverloads + fun create(params: AccessTokenCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see [create] */ fun create( params: AccessTokenCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [AccessTokenServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /auth/token`, but is otherwise the same as + * [AccessTokenServiceAsync.create]. + */ + @MustBeClosed + fun create( + params: AccessTokenCreateParams + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: AccessTokenCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccessTokenServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccessTokenServiceAsyncImpl.kt index 3a5a40a0..6ad0bf71 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccessTokenServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccessTokenServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,71 +11,94 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.errors.FinchException import com.tryfinch.api.models.AccessTokenCreateParams import com.tryfinch.api.models.CreateAccessTokenResponse import java.util.concurrent.CompletableFuture +import kotlin.jvm.optionals.getOrNull class AccessTokenServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : AccessTokenServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: AccessTokenServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): AccessTokenServiceAsync.WithRawResponse = withRawResponse - /** Exchange the authorization code for an access token */ override fun create( params: AccessTokenCreateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val builder = params.toBuilder() + ): CompletableFuture = + // post /auth/token + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AccessTokenServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: AccessTokenCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val builder = params.toBuilder() - if (!params.clientSecret().isPresent) { - if (clientOptions.clientSecret == null || clientOptions.clientSecret.isEmpty()) { - throw FinchException( - "client_secret must be provided as an argument or with the FINCH_CLIENT_SECRET environment variable" - ) + if (!params.clientSecret().isPresent) { + val clientSecret = clientOptions.clientSecret().getOrNull() + if (clientSecret.isNullOrEmpty()) { + throw FinchException( + "client_secret must be provided as an argument or with the FINCH_CLIENT_SECRET environment variable" + ) + } + builder.clientSecret(clientSecret) } - builder.clientSecret(clientOptions.clientSecret) - } - if (!params.clientId().isPresent) { - if (clientOptions.clientId == null || clientOptions.clientId.isEmpty()) { - throw FinchException( - "client_id must be provided as an argument or with the FINCH_CLIENT_ID environment variable" - ) + if (!params.clientId().isPresent) { + val clientId = clientOptions.clientId().getOrNull() + if (clientId.isNullOrEmpty()) { + throw FinchException( + "client_id must be provided as an argument or with the FINCH_CLIENT_ID environment variable" + ) + } + builder.clientId(clientId) } - builder.clientId(clientOptions.clientId) - } - val modifiedParams = builder.build() + val modifiedParams = builder.build() - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("auth", "token") - .putAllQueryParams(clientOptions.queryParams) - .replaceAllQueryParams(params._queryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params._headers()) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("auth", "token") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(modifiedParams._queryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(modifiedParams._headers()) + .body(json(clientOptions.jsonMapper, modifiedParams._body())) + .build() + .prepareAsync(clientOptions, modifiedParams) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccountServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccountServiceAsync.kt index f40cf58d..787a514b 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccountServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccountServiceAsync.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.AccountDisconnectParams import com.tryfinch.api.models.AccountIntrospectParams import com.tryfinch.api.models.DisconnectResponse @@ -13,25 +13,109 @@ import java.util.concurrent.CompletableFuture interface AccountServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Disconnect one or more `access_token`s from your application. */ - @JvmOverloads + fun disconnect(): CompletableFuture = + disconnect(AccountDisconnectParams.none()) + + /** @see [disconnect] */ fun disconnect( params: AccountDisconnectParams = AccountDisconnectParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** Disconnect one or more `access_token`s from your application. */ + /** @see [disconnect] */ + fun disconnect( + params: AccountDisconnectParams = AccountDisconnectParams.none() + ): CompletableFuture = disconnect(params, RequestOptions.none()) + + /** @see [disconnect] */ fun disconnect(requestOptions: RequestOptions): CompletableFuture = disconnect(AccountDisconnectParams.none(), requestOptions) /** Read account information associated with an `access_token` */ - @JvmOverloads + fun introspect(): CompletableFuture = introspect(AccountIntrospectParams.none()) + + /** @see [introspect] */ fun introspect( params: AccountIntrospectParams = AccountIntrospectParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** Read account information associated with an `access_token` */ + /** @see [introspect] */ + fun introspect( + params: AccountIntrospectParams = AccountIntrospectParams.none() + ): CompletableFuture = introspect(params, RequestOptions.none()) + + /** @see [introspect] */ fun introspect(requestOptions: RequestOptions): CompletableFuture = introspect(AccountIntrospectParams.none(), requestOptions) + + /** + * A view of [AccountServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /disconnect`, but is otherwise the same as + * [AccountServiceAsync.disconnect]. + */ + @MustBeClosed + fun disconnect(): CompletableFuture> = + disconnect(AccountDisconnectParams.none()) + + /** @see [disconnect] */ + @MustBeClosed + fun disconnect( + params: AccountDisconnectParams = AccountDisconnectParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [disconnect] */ + @MustBeClosed + fun disconnect( + params: AccountDisconnectParams = AccountDisconnectParams.none() + ): CompletableFuture> = + disconnect(params, RequestOptions.none()) + + /** @see [disconnect] */ + @MustBeClosed + fun disconnect( + requestOptions: RequestOptions + ): CompletableFuture> = + disconnect(AccountDisconnectParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /introspect`, but is otherwise the same as + * [AccountServiceAsync.introspect]. + */ + @MustBeClosed + fun introspect(): CompletableFuture> = + introspect(AccountIntrospectParams.none()) + + /** @see [introspect] */ + @MustBeClosed + fun introspect( + params: AccountIntrospectParams = AccountIntrospectParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [introspect] */ + @MustBeClosed + fun introspect( + params: AccountIntrospectParams = AccountIntrospectParams.none() + ): CompletableFuture> = + introspect(params, RequestOptions.none()) + + /** @see [introspect] */ + @MustBeClosed + fun introspect( + requestOptions: RequestOptions + ): CompletableFuture> = + introspect(AccountIntrospectParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccountServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccountServiceAsyncImpl.kt index 218b9c5d..dc00271c 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccountServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/AccountServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.AccountDisconnectParams import com.tryfinch.api.models.AccountIntrospectParams import com.tryfinch.api.models.DisconnectResponse @@ -22,60 +24,88 @@ import java.util.concurrent.CompletableFuture class AccountServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : AccountServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: AccountServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val disconnectHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): AccountServiceAsync.WithRawResponse = withRawResponse - /** Disconnect one or more `access_token`s from your application. */ override fun disconnect( params: AccountDisconnectParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("disconnect") - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { disconnectHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } + ): CompletableFuture = + // post /disconnect + withRawResponse().disconnect(params, requestOptions).thenApply { it.parse() } - private val introspectHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Read account information associated with an `access_token` */ override fun introspect( params: AccountIntrospectParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("introspect") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { introspectHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // get /introspect + withRawResponse().introspect(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AccountServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val disconnectHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun disconnect( + params: AccountDisconnectParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("disconnect") + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { disconnectHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val introspectHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun introspect( + params: AccountIntrospectParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("introspect") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { introspectHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ConnectServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ConnectServiceAsync.kt index 7029f435..53ceda78 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ConnectServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ConnectServiceAsync.kt @@ -6,5 +6,18 @@ import com.tryfinch.api.services.async.connect.SessionServiceAsync interface ConnectServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun sessions(): SessionServiceAsync + + /** + * A view of [ConnectServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + fun sessions(): SessionServiceAsync.WithRawResponse + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ConnectServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ConnectServiceAsyncImpl.kt index a019a5c1..f93bc643 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ConnectServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ConnectServiceAsyncImpl.kt @@ -9,7 +9,23 @@ import com.tryfinch.api.services.async.connect.SessionServiceAsyncImpl class ConnectServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : ConnectServiceAsync { + private val withRawResponse: ConnectServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val sessions: SessionServiceAsync by lazy { SessionServiceAsyncImpl(clientOptions) } + override fun withRawResponse(): ConnectServiceAsync.WithRawResponse = withRawResponse + override fun sessions(): SessionServiceAsync = sessions + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ConnectServiceAsync.WithRawResponse { + + private val sessions: SessionServiceAsync.WithRawResponse by lazy { + SessionServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun sessions(): SessionServiceAsync.WithRawResponse = sessions + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/HrisServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/HrisServiceAsync.kt index 1e10b682..9a2feba1 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/HrisServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/HrisServiceAsync.kt @@ -13,6 +13,11 @@ import com.tryfinch.api.services.async.hris.PaymentServiceAsync interface HrisServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun company(): CompanyServiceAsync fun directory(): DirectoryServiceAsync @@ -28,4 +33,24 @@ interface HrisServiceAsync { fun documents(): DocumentServiceAsync fun benefits(): BenefitServiceAsync + + /** A view of [HrisServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun company(): CompanyServiceAsync.WithRawResponse + + fun directory(): DirectoryServiceAsync.WithRawResponse + + fun individuals(): IndividualServiceAsync.WithRawResponse + + fun employments(): EmploymentServiceAsync.WithRawResponse + + fun payments(): PaymentServiceAsync.WithRawResponse + + fun payStatements(): PayStatementServiceAsync.WithRawResponse + + fun documents(): DocumentServiceAsync.WithRawResponse + + fun benefits(): BenefitServiceAsync.WithRawResponse + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/HrisServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/HrisServiceAsyncImpl.kt index 913a435f..93d03324 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/HrisServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/HrisServiceAsyncImpl.kt @@ -23,6 +23,10 @@ import com.tryfinch.api.services.async.hris.PaymentServiceAsyncImpl class HrisServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : HrisServiceAsync { + private val withRawResponse: HrisServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val company: CompanyServiceAsync by lazy { CompanyServiceAsyncImpl(clientOptions) } private val directory: DirectoryServiceAsync by lazy { @@ -47,6 +51,8 @@ class HrisServiceAsyncImpl internal constructor(private val clientOptions: Clien private val benefits: BenefitServiceAsync by lazy { BenefitServiceAsyncImpl(clientOptions) } + override fun withRawResponse(): HrisServiceAsync.WithRawResponse = withRawResponse + override fun company(): CompanyServiceAsync = company override fun directory(): DirectoryServiceAsync = directory @@ -62,4 +68,56 @@ class HrisServiceAsyncImpl internal constructor(private val clientOptions: Clien override fun documents(): DocumentServiceAsync = documents override fun benefits(): BenefitServiceAsync = benefits + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + HrisServiceAsync.WithRawResponse { + + private val company: CompanyServiceAsync.WithRawResponse by lazy { + CompanyServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val directory: DirectoryServiceAsync.WithRawResponse by lazy { + DirectoryServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val individuals: IndividualServiceAsync.WithRawResponse by lazy { + IndividualServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val employments: EmploymentServiceAsync.WithRawResponse by lazy { + EmploymentServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val payments: PaymentServiceAsync.WithRawResponse by lazy { + PaymentServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val payStatements: PayStatementServiceAsync.WithRawResponse by lazy { + PayStatementServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val documents: DocumentServiceAsync.WithRawResponse by lazy { + DocumentServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val benefits: BenefitServiceAsync.WithRawResponse by lazy { + BenefitServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun company(): CompanyServiceAsync.WithRawResponse = company + + override fun directory(): DirectoryServiceAsync.WithRawResponse = directory + + override fun individuals(): IndividualServiceAsync.WithRawResponse = individuals + + override fun employments(): EmploymentServiceAsync.WithRawResponse = employments + + override fun payments(): PaymentServiceAsync.WithRawResponse = payments + + override fun payStatements(): PayStatementServiceAsync.WithRawResponse = payStatements + + override fun documents(): DocumentServiceAsync.WithRawResponse = documents + + override fun benefits(): BenefitServiceAsync.WithRawResponse = benefits + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/JobServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/JobServiceAsync.kt index 312850ad..5b415166 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/JobServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/JobServiceAsync.kt @@ -7,7 +7,20 @@ import com.tryfinch.api.services.async.jobs.ManualServiceAsync interface JobServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun automated(): AutomatedServiceAsync fun manual(): ManualServiceAsync + + /** A view of [JobServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun automated(): AutomatedServiceAsync.WithRawResponse + + fun manual(): ManualServiceAsync.WithRawResponse + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/JobServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/JobServiceAsyncImpl.kt index 264fb526..5849135c 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/JobServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/JobServiceAsyncImpl.kt @@ -11,13 +11,35 @@ import com.tryfinch.api.services.async.jobs.ManualServiceAsyncImpl class JobServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : JobServiceAsync { + private val withRawResponse: JobServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val automated: AutomatedServiceAsync by lazy { AutomatedServiceAsyncImpl(clientOptions) } private val manual: ManualServiceAsync by lazy { ManualServiceAsyncImpl(clientOptions) } + override fun withRawResponse(): JobServiceAsync.WithRawResponse = withRawResponse + override fun automated(): AutomatedServiceAsync = automated override fun manual(): ManualServiceAsync = manual + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + JobServiceAsync.WithRawResponse { + + private val automated: AutomatedServiceAsync.WithRawResponse by lazy { + AutomatedServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val manual: ManualServiceAsync.WithRawResponse by lazy { + ManualServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun automated(): AutomatedServiceAsync.WithRawResponse = automated + + override fun manual(): ManualServiceAsync.WithRawResponse = manual + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/PayrollServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/PayrollServiceAsync.kt index b7a093e1..66caaaaa 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/PayrollServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/PayrollServiceAsync.kt @@ -6,5 +6,18 @@ import com.tryfinch.api.services.async.payroll.PayGroupServiceAsync interface PayrollServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun payGroups(): PayGroupServiceAsync + + /** + * A view of [PayrollServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + fun payGroups(): PayGroupServiceAsync.WithRawResponse + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/PayrollServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/PayrollServiceAsyncImpl.kt index a856537b..6c3ca41f 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/PayrollServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/PayrollServiceAsyncImpl.kt @@ -9,7 +9,23 @@ import com.tryfinch.api.services.async.payroll.PayGroupServiceAsyncImpl class PayrollServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : PayrollServiceAsync { + private val withRawResponse: PayrollServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val payGroups: PayGroupServiceAsync by lazy { PayGroupServiceAsyncImpl(clientOptions) } + override fun withRawResponse(): PayrollServiceAsync.WithRawResponse = withRawResponse + override fun payGroups(): PayGroupServiceAsync = payGroups + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PayrollServiceAsync.WithRawResponse { + + private val payGroups: PayGroupServiceAsync.WithRawResponse by lazy { + PayGroupServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun payGroups(): PayGroupServiceAsync.WithRawResponse = payGroups + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ProviderServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ProviderServiceAsync.kt index 954bba83..4f112fda 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ProviderServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ProviderServiceAsync.kt @@ -1,24 +1,71 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.ProviderListPageAsync import com.tryfinch.api.models.ProviderListParams import java.util.concurrent.CompletableFuture interface ProviderServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Return details on all available payroll and HR systems. */ - @JvmOverloads + fun list(): CompletableFuture = list(ProviderListParams.none()) + + /** @see [list] */ fun list( params: ProviderListParams = ProviderListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** Return details on all available payroll and HR systems. */ + /** @see [list] */ + fun list( + params: ProviderListParams = ProviderListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see [list] */ fun list(requestOptions: RequestOptions): CompletableFuture = list(ProviderListParams.none(), requestOptions) + + /** + * A view of [ProviderServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /providers`, but is otherwise the same as + * [ProviderServiceAsync.list]. + */ + @MustBeClosed + fun list(): CompletableFuture> = + list(ProviderListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: ProviderListParams = ProviderListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [list] */ + @MustBeClosed + fun list( + params: ProviderListParams = ProviderListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(ProviderListParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ProviderServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ProviderServiceAsyncImpl.kt index 08227c2a..a4579fe2 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ProviderServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/ProviderServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,8 +11,9 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.Provider import com.tryfinch.api.models.ProviderListPageAsync import com.tryfinch.api.models.ProviderListParams @@ -20,39 +22,58 @@ import java.util.concurrent.CompletableFuture class ProviderServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : ProviderServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ProviderServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val listHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): ProviderServiceAsync.WithRawResponse = withRawResponse - /** Return details on all available payroll and HR systems. */ override fun list( params: ProviderListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("providers") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } - } - .let { - ProviderListPageAsync.of( - this, - params, - ProviderListPageAsync.Response.builder().items(it).build(), - ) + ): CompletableFuture = + // get /providers + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ProviderServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun list( + params: ProviderListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("providers") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + ProviderListPageAsync.of( + ProviderServiceAsyncImpl(clientOptions), + params, + ProviderListPageAsync.Response.builder().items(it).build(), + ) + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/RequestForwardingServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/RequestForwardingServiceAsync.kt index 824ada2d..323e5566 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/RequestForwardingServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/RequestForwardingServiceAsync.kt @@ -1,24 +1,57 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.RequestForwardingForwardParams import com.tryfinch.api.models.RequestForwardingForwardResponse import java.util.concurrent.CompletableFuture interface RequestForwardingServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** * The Forward API allows you to make direct requests to an employment system. If Finch’s * unified API doesn’t have a data model that cleanly fits your needs, then Forward allows you * to push or pull data models directly against an integration’s API. */ - @JvmOverloads + fun forward( + params: RequestForwardingForwardParams + ): CompletableFuture = forward(params, RequestOptions.none()) + + /** @see [forward] */ fun forward( params: RequestForwardingForwardParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [RequestForwardingServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /forward`, but is otherwise the same as + * [RequestForwardingServiceAsync.forward]. + */ + @MustBeClosed + fun forward( + params: RequestForwardingForwardParams + ): CompletableFuture> = + forward(params, RequestOptions.none()) + + /** @see [forward] */ + @MustBeClosed + fun forward( + params: RequestForwardingForwardParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/RequestForwardingServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/RequestForwardingServiceAsyncImpl.kt index bcc50f5c..25b6c483 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/RequestForwardingServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/RequestForwardingServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.RequestForwardingForwardParams import com.tryfinch.api.models.RequestForwardingForwardResponse import java.util.concurrent.CompletableFuture @@ -20,38 +22,53 @@ import java.util.concurrent.CompletableFuture class RequestForwardingServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : RequestForwardingServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: RequestForwardingServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val forwardHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): RequestForwardingServiceAsync.WithRawResponse = withRawResponse - /** - * The Forward API allows you to make direct requests to an employment system. If Finch’s - * unified API doesn’t have a data model that cleanly fits your needs, then Forward allows you - * to push or pull data models directly against an integration’s API. - */ override fun forward( params: RequestForwardingForwardParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("forward") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { forwardHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // post /forward + withRawResponse().forward(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + RequestForwardingServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val forwardHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun forward( + params: RequestForwardingForwardParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("forward") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { forwardHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/SandboxServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/SandboxServiceAsync.kt index ca38451b..d7cf62b6 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/SandboxServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/SandboxServiceAsync.kt @@ -12,6 +12,11 @@ import com.tryfinch.api.services.async.sandbox.PaymentServiceAsync interface SandboxServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun connections(): ConnectionServiceAsync fun company(): CompanyServiceAsync @@ -25,4 +30,24 @@ interface SandboxServiceAsync { fun payment(): PaymentServiceAsync fun jobs(): JobServiceAsync + + /** + * A view of [SandboxServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + fun connections(): ConnectionServiceAsync.WithRawResponse + + fun company(): CompanyServiceAsync.WithRawResponse + + fun directory(): DirectoryServiceAsync.WithRawResponse + + fun individual(): IndividualServiceAsync.WithRawResponse + + fun employment(): EmploymentServiceAsync.WithRawResponse + + fun payment(): PaymentServiceAsync.WithRawResponse + + fun jobs(): JobServiceAsync.WithRawResponse + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/SandboxServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/SandboxServiceAsyncImpl.kt index d68cb53a..409d5daf 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/SandboxServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/SandboxServiceAsyncImpl.kt @@ -21,6 +21,10 @@ import com.tryfinch.api.services.async.sandbox.PaymentServiceAsyncImpl class SandboxServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : SandboxServiceAsync { + private val withRawResponse: SandboxServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val connections: ConnectionServiceAsync by lazy { ConnectionServiceAsyncImpl(clientOptions) } @@ -43,6 +47,8 @@ class SandboxServiceAsyncImpl internal constructor(private val clientOptions: Cl private val jobs: JobServiceAsync by lazy { JobServiceAsyncImpl(clientOptions) } + override fun withRawResponse(): SandboxServiceAsync.WithRawResponse = withRawResponse + override fun connections(): ConnectionServiceAsync = connections override fun company(): CompanyServiceAsync = company @@ -56,4 +62,50 @@ class SandboxServiceAsyncImpl internal constructor(private val clientOptions: Cl override fun payment(): PaymentServiceAsync = payment override fun jobs(): JobServiceAsync = jobs + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + SandboxServiceAsync.WithRawResponse { + + private val connections: ConnectionServiceAsync.WithRawResponse by lazy { + ConnectionServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val company: CompanyServiceAsync.WithRawResponse by lazy { + CompanyServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val directory: DirectoryServiceAsync.WithRawResponse by lazy { + DirectoryServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val individual: IndividualServiceAsync.WithRawResponse by lazy { + IndividualServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val employment: EmploymentServiceAsync.WithRawResponse by lazy { + EmploymentServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val payment: PaymentServiceAsync.WithRawResponse by lazy { + PaymentServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val jobs: JobServiceAsync.WithRawResponse by lazy { + JobServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun connections(): ConnectionServiceAsync.WithRawResponse = connections + + override fun company(): CompanyServiceAsync.WithRawResponse = company + + override fun directory(): DirectoryServiceAsync.WithRawResponse = directory + + override fun individual(): IndividualServiceAsync.WithRawResponse = individual + + override fun employment(): EmploymentServiceAsync.WithRawResponse = employment + + override fun payment(): PaymentServiceAsync.WithRawResponse = payment + + override fun jobs(): JobServiceAsync.WithRawResponse = jobs + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/WebhookServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/WebhookServiceAsyncImpl.kt index 598b6b8e..594a5792 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/WebhookServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/WebhookServiceAsyncImpl.kt @@ -5,10 +5,7 @@ package com.tryfinch.api.services.async import com.fasterxml.jackson.core.JsonProcessingException import com.tryfinch.api.core.ClientOptions import com.tryfinch.api.core.getRequiredHeader -import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.http.Headers -import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.errors.FinchException import com.tryfinch.api.models.WebhookEvent import java.security.MessageDigest @@ -17,12 +14,11 @@ import java.time.Instant import java.util.Base64 import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec +import kotlin.jvm.optionals.getOrNull class WebhookServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : WebhookServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) - override fun unwrap(payload: String, headers: Headers, secret: String?): WebhookEvent { verifySignature(payload, headers, secret) return try { @@ -35,7 +31,7 @@ class WebhookServiceAsyncImpl internal constructor(private val clientOptions: Cl override fun verifySignature(payload: String, headers: Headers, secret: String?) { val webhookSecret = secret - ?: clientOptions.webhookSecret + ?: clientOptions.webhookSecret().getOrNull() ?: throw FinchException( "The webhook secret must either be set using the env var, FINCH_WEBHOOK_SECRET, on the client class, or passed to this method" ) diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/connect/SessionServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/connect/SessionServiceAsync.kt index e79109d7..3b1e18cb 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/connect/SessionServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/connect/SessionServiceAsync.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.connect +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.ConnectSessionNewParams import com.tryfinch.api.models.ConnectSessionReauthenticateParams import com.tryfinch.api.models.SessionNewResponse @@ -13,17 +13,70 @@ import java.util.concurrent.CompletableFuture interface SessionServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Create a new connect session for an employer */ - @JvmOverloads + fun new_(params: ConnectSessionNewParams): CompletableFuture = + new_(params, RequestOptions.none()) + + /** @see [new_] */ fun new_( params: ConnectSessionNewParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture /** Create a new Connect session for reauthenticating an existing connection */ - @JvmOverloads + fun reauthenticate( + params: ConnectSessionReauthenticateParams + ): CompletableFuture = + reauthenticate(params, RequestOptions.none()) + + /** @see [reauthenticate] */ fun reauthenticate( params: ConnectSessionReauthenticateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [SessionServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /connect/sessions`, but is otherwise the same as + * [SessionServiceAsync.new_]. + */ + @MustBeClosed + fun new_( + params: ConnectSessionNewParams + ): CompletableFuture> = + new_(params, RequestOptions.none()) + + /** @see [new_] */ + @MustBeClosed + fun new_( + params: ConnectSessionNewParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `post /connect/sessions/reauthenticate`, but is otherwise + * the same as [SessionServiceAsync.reauthenticate]. + */ + @MustBeClosed + fun reauthenticate( + params: ConnectSessionReauthenticateParams + ): CompletableFuture> = + reauthenticate(params, RequestOptions.none()) + + /** @see [reauthenticate] */ + @MustBeClosed + fun reauthenticate( + params: ConnectSessionReauthenticateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/connect/SessionServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/connect/SessionServiceAsyncImpl.kt index 385c1cb5..b703391c 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/connect/SessionServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/connect/SessionServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.connect import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.ConnectSessionNewParams import com.tryfinch.api.models.ConnectSessionReauthenticateParams import com.tryfinch.api.models.SessionNewResponse @@ -22,62 +24,90 @@ import java.util.concurrent.CompletableFuture class SessionServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : SessionServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: SessionServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val newHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): SessionServiceAsync.WithRawResponse = withRawResponse - /** Create a new connect session for an employer */ override fun new_( params: ConnectSessionNewParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("connect", "sessions") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { newHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } + ): CompletableFuture = + // post /connect/sessions + withRawResponse().new_(params, requestOptions).thenApply { it.parse() } - private val reauthenticateHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Create a new Connect session for reauthenticating an existing connection */ override fun reauthenticate( params: ConnectSessionReauthenticateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("connect", "sessions", "reauthenticate") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { reauthenticateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // post /connect/sessions/reauthenticate + withRawResponse().reauthenticate(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + SessionServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val newHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun new_( + params: ConnectSessionNewParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("connect", "sessions") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { newHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val reauthenticateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun reauthenticate( + params: ConnectSessionReauthenticateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("connect", "sessions", "reauthenticate") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { reauthenticateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/BenefitServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/BenefitServiceAsync.kt index c764d97d..0ebd8f70 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/BenefitServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/BenefitServiceAsync.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.CompanyBenefit import com.tryfinch.api.models.CreateCompanyBenefitsResponse import com.tryfinch.api.models.HrisBenefitCreateParams @@ -20,61 +20,226 @@ import java.util.concurrent.CompletableFuture interface BenefitServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun individuals(): IndividualServiceAsync /** * Creates a new company-wide deduction or contribution. Please use the `/providers` endpoint to * view available types for each provider. */ - @JvmOverloads + fun create(): CompletableFuture = + create(HrisBenefitCreateParams.none()) + + /** @see [create] */ fun create( params: HrisBenefitCreateParams = HrisBenefitCreateParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** - * Creates a new company-wide deduction or contribution. Please use the `/providers` endpoint to - * view available types for each provider. - */ + /** @see [create] */ + fun create( + params: HrisBenefitCreateParams = HrisBenefitCreateParams.none() + ): CompletableFuture = create(params, RequestOptions.none()) + + /** @see [create] */ fun create(requestOptions: RequestOptions): CompletableFuture = create(HrisBenefitCreateParams.none(), requestOptions) /** Lists deductions and contributions information for a given item */ - @JvmOverloads + fun retrieve(params: HrisBenefitRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ fun retrieve( params: HrisBenefitRetrieveParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture /** Updates an existing company-wide deduction or contribution */ - @JvmOverloads + fun update(params: HrisBenefitUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see [update] */ fun update( params: HrisBenefitUpdateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture /** List all company-wide deductions and contributions. */ - @JvmOverloads + fun list(): CompletableFuture = list(HrisBenefitListParams.none()) + + /** @see [list] */ fun list( params: HrisBenefitListParams = HrisBenefitListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** List all company-wide deductions and contributions. */ + /** @see [list] */ + fun list( + params: HrisBenefitListParams = HrisBenefitListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see [list] */ fun list(requestOptions: RequestOptions): CompletableFuture = list(HrisBenefitListParams.none(), requestOptions) /** Get deductions metadata */ - @JvmOverloads + fun listSupportedBenefits(): CompletableFuture = + listSupportedBenefits(HrisBenefitListSupportedBenefitsParams.none()) + + /** @see [listSupportedBenefits] */ fun listSupportedBenefits( params: HrisBenefitListSupportedBenefitsParams = HrisBenefitListSupportedBenefitsParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** Get deductions metadata */ + /** @see [listSupportedBenefits] */ + fun listSupportedBenefits( + params: HrisBenefitListSupportedBenefitsParams = + HrisBenefitListSupportedBenefitsParams.none() + ): CompletableFuture = + listSupportedBenefits(params, RequestOptions.none()) + + /** @see [listSupportedBenefits] */ fun listSupportedBenefits( requestOptions: RequestOptions ): CompletableFuture = listSupportedBenefits(HrisBenefitListSupportedBenefitsParams.none(), requestOptions) + + /** + * A view of [BenefitServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + fun individuals(): IndividualServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /employer/benefits`, but is otherwise the same as + * [BenefitServiceAsync.create]. + */ + @MustBeClosed + fun create(): CompletableFuture> = + create(HrisBenefitCreateParams.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: HrisBenefitCreateParams = HrisBenefitCreateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [create] */ + @MustBeClosed + fun create( + params: HrisBenefitCreateParams = HrisBenefitCreateParams.none() + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + requestOptions: RequestOptions + ): CompletableFuture> = + create(HrisBenefitCreateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /employer/benefits/{benefit_id}`, but is otherwise + * the same as [BenefitServiceAsync.retrieve]. + */ + @MustBeClosed + fun retrieve( + params: HrisBenefitRetrieveParams + ): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: HrisBenefitRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `post /employer/benefits/{benefit_id}`, but is otherwise + * the same as [BenefitServiceAsync.update]. + */ + @MustBeClosed + fun update( + params: HrisBenefitUpdateParams + ): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: HrisBenefitUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /employer/benefits`, but is otherwise the same as + * [BenefitServiceAsync.list]. + */ + @MustBeClosed + fun list(): CompletableFuture> = + list(HrisBenefitListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisBenefitListParams = HrisBenefitListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisBenefitListParams = HrisBenefitListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(HrisBenefitListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /employer/benefits/meta`, but is otherwise the same + * as [BenefitServiceAsync.listSupportedBenefits]. + */ + @MustBeClosed + fun listSupportedBenefits(): + CompletableFuture> = + listSupportedBenefits(HrisBenefitListSupportedBenefitsParams.none()) + + /** @see [listSupportedBenefits] */ + @MustBeClosed + fun listSupportedBenefits( + params: HrisBenefitListSupportedBenefitsParams = + HrisBenefitListSupportedBenefitsParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [listSupportedBenefits] */ + @MustBeClosed + fun listSupportedBenefits( + params: HrisBenefitListSupportedBenefitsParams = + HrisBenefitListSupportedBenefitsParams.none() + ): CompletableFuture> = + listSupportedBenefits(params, RequestOptions.none()) + + /** @see [listSupportedBenefits] */ + @MustBeClosed + fun listSupportedBenefits( + requestOptions: RequestOptions + ): CompletableFuture> = + listSupportedBenefits(HrisBenefitListSupportedBenefitsParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/BenefitServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/BenefitServiceAsyncImpl.kt index 88f2f69f..b44c2818 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/BenefitServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/BenefitServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.CompanyBenefit import com.tryfinch.api.models.CreateCompanyBenefitsResponse import com.tryfinch.api.models.HrisBenefitCreateParams @@ -31,169 +33,229 @@ import java.util.concurrent.CompletableFuture class BenefitServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : BenefitServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: BenefitServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } private val individuals: IndividualServiceAsync by lazy { IndividualServiceAsyncImpl(clientOptions) } - override fun individuals(): IndividualServiceAsync = individuals + override fun withRawResponse(): BenefitServiceAsync.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun individuals(): IndividualServiceAsync = individuals - /** - * Creates a new company-wide deduction or contribution. Please use the `/providers` endpoint to - * view available types for each provider. - */ override fun create( params: HrisBenefitCreateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("employer", "benefits") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } + ): CompletableFuture = + // post /employer/benefits + withRawResponse().create(params, requestOptions).thenApply { it.parse() } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Lists deductions and contributions information for a given item */ override fun retrieve( params: HrisBenefitRetrieveParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "benefits", params.getPathParam(0)) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { retrieveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } - - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + ): CompletableFuture = + // get /employer/benefits/{benefit_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } - /** Updates an existing company-wide deduction or contribution */ override fun update( params: HrisBenefitUpdateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("employer", "benefits", params.getPathParam(0)) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } + ): CompletableFuture = + // post /employer/benefits/{benefit_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } - private val listHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** List all company-wide deductions and contributions. */ override fun list( params: HrisBenefitListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "benefits") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } - } - .let { - HrisBenefitListPageAsync.of( - this, - params, - HrisBenefitListPageAsync.Response.builder().items(it).build(), - ) - } - } - } + ): CompletableFuture = + // get /employer/benefits + withRawResponse().list(params, requestOptions).thenApply { it.parse() } - private val listSupportedBenefitsHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Get deductions metadata */ override fun listSupportedBenefits( params: HrisBenefitListSupportedBenefitsParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "benefits", "meta") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listSupportedBenefitsHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } + ): CompletableFuture = + // get /employer/benefits/meta + withRawResponse().listSupportedBenefits(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + BenefitServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val individuals: IndividualServiceAsync.WithRawResponse by lazy { + IndividualServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun individuals(): IndividualServiceAsync.WithRawResponse = individuals + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: HrisBenefitCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("employer", "benefits") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun retrieve( + params: HrisBenefitRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "benefits", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - .let { - HrisBenefitListSupportedBenefitsPageAsync.of( - this, - params, - HrisBenefitListSupportedBenefitsPageAsync.Response.builder() - .items(it) - .build(), - ) + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun update( + params: HrisBenefitUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("employer", "benefits", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun list( + params: HrisBenefitListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "benefits") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + HrisBenefitListPageAsync.of( + BenefitServiceAsyncImpl(clientOptions), + params, + HrisBenefitListPageAsync.Response.builder().items(it).build(), + ) + } + } + } + } + + private val listSupportedBenefitsHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun listSupportedBenefits( + params: HrisBenefitListSupportedBenefitsParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "benefits", "meta") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { listSupportedBenefitsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + HrisBenefitListSupportedBenefitsPageAsync.of( + BenefitServiceAsyncImpl(clientOptions), + params, + HrisBenefitListSupportedBenefitsPageAsync.Response.builder() + .items(it) + .build(), + ) + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/CompanyServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/CompanyServiceAsync.kt index aaee4fc4..cfdf2ff3 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/CompanyServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/CompanyServiceAsync.kt @@ -1,24 +1,73 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.Company import com.tryfinch.api.models.HrisCompanyRetrieveParams +import com.tryfinch.api.services.async.hris.company.PayStatementItemServiceAsync import java.util.concurrent.CompletableFuture interface CompanyServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + fun payStatementItem(): PayStatementItemServiceAsync + /** Read basic company data */ - @JvmOverloads + fun retrieve(): CompletableFuture = retrieve(HrisCompanyRetrieveParams.none()) + + /** @see [retrieve] */ fun retrieve( params: HrisCompanyRetrieveParams = HrisCompanyRetrieveParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** Read basic company data */ + /** @see [retrieve] */ + fun retrieve( + params: HrisCompanyRetrieveParams = HrisCompanyRetrieveParams.none() + ): CompletableFuture = retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ fun retrieve(requestOptions: RequestOptions): CompletableFuture = retrieve(HrisCompanyRetrieveParams.none(), requestOptions) + + /** + * A view of [CompanyServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + fun payStatementItem(): PayStatementItemServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /employer/company`, but is otherwise the same as + * [CompanyServiceAsync.retrieve]. + */ + @MustBeClosed + fun retrieve(): CompletableFuture> = + retrieve(HrisCompanyRetrieveParams.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: HrisCompanyRetrieveParams = HrisCompanyRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: HrisCompanyRetrieveParams = HrisCompanyRetrieveParams.none() + ): CompletableFuture> = retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve(requestOptions: RequestOptions): CompletableFuture> = + retrieve(HrisCompanyRetrieveParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/CompanyServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/CompanyServiceAsyncImpl.kt index 36830f68..36674057 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/CompanyServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/CompanyServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,41 +11,76 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.Company import com.tryfinch.api.models.HrisCompanyRetrieveParams +import com.tryfinch.api.services.async.hris.company.PayStatementItemServiceAsync +import com.tryfinch.api.services.async.hris.company.PayStatementItemServiceAsyncImpl import java.util.concurrent.CompletableFuture class CompanyServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : CompanyServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: CompanyServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val payStatementItem: PayStatementItemServiceAsync by lazy { + PayStatementItemServiceAsyncImpl(clientOptions) + } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): CompanyServiceAsync.WithRawResponse = withRawResponse + + override fun payStatementItem(): PayStatementItemServiceAsync = payStatementItem - /** Read basic company data */ override fun retrieve( params: HrisCompanyRetrieveParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "company") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { retrieveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // get /employer/company + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + CompanyServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val payStatementItem: PayStatementItemServiceAsync.WithRawResponse by lazy { + PayStatementItemServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun payStatementItem(): PayStatementItemServiceAsync.WithRawResponse = + payStatementItem + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun retrieve( + params: HrisCompanyRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "company") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DirectoryServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DirectoryServiceAsync.kt index 01ae6ff8..83b5b834 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DirectoryServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DirectoryServiceAsync.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.HrisDirectoryListIndividualsPageAsync import com.tryfinch.api.models.HrisDirectoryListIndividualsParams import com.tryfinch.api.models.HrisDirectoryListPageAsync @@ -13,29 +13,121 @@ import java.util.concurrent.CompletableFuture interface DirectoryServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Read company directory and organization structure */ - @JvmOverloads + fun list(): CompletableFuture = list(HrisDirectoryListParams.none()) + + /** @see [list] */ fun list( params: HrisDirectoryListParams = HrisDirectoryListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** Read company directory and organization structure */ + /** @see [list] */ + fun list( + params: HrisDirectoryListParams = HrisDirectoryListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see [list] */ fun list(requestOptions: RequestOptions): CompletableFuture = list(HrisDirectoryListParams.none(), requestOptions) /** Read company directory and organization structure */ @Deprecated("use `list` instead") - @JvmOverloads + fun listIndividuals(): CompletableFuture = + listIndividuals(HrisDirectoryListIndividualsParams.none()) + + /** @see [listIndividuals] */ + @Deprecated("use `list` instead") fun listIndividuals( params: HrisDirectoryListIndividualsParams = HrisDirectoryListIndividualsParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** Read company directory and organization structure */ + /** @see [listIndividuals] */ + @Deprecated("use `list` instead") + fun listIndividuals( + params: HrisDirectoryListIndividualsParams = HrisDirectoryListIndividualsParams.none() + ): CompletableFuture = + listIndividuals(params, RequestOptions.none()) + + /** @see [listIndividuals] */ @Deprecated("use `list` instead") fun listIndividuals( requestOptions: RequestOptions ): CompletableFuture = listIndividuals(HrisDirectoryListIndividualsParams.none(), requestOptions) + + /** + * A view of [DirectoryServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /employer/directory`, but is otherwise the same as + * [DirectoryServiceAsync.list]. + */ + @MustBeClosed + fun list(): CompletableFuture> = + list(HrisDirectoryListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisDirectoryListParams = HrisDirectoryListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisDirectoryListParams = HrisDirectoryListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(HrisDirectoryListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /employer/directory`, but is otherwise the same as + * [DirectoryServiceAsync.listIndividuals]. + */ + @Deprecated("use `list` instead") + @MustBeClosed + fun listIndividuals(): + CompletableFuture> = + listIndividuals(HrisDirectoryListIndividualsParams.none()) + + /** @see [listIndividuals] */ + @Deprecated("use `list` instead") + @MustBeClosed + fun listIndividuals( + params: HrisDirectoryListIndividualsParams = HrisDirectoryListIndividualsParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [listIndividuals] */ + @Deprecated("use `list` instead") + @MustBeClosed + fun listIndividuals( + params: HrisDirectoryListIndividualsParams = HrisDirectoryListIndividualsParams.none() + ): CompletableFuture> = + listIndividuals(params, RequestOptions.none()) + + /** @see [listIndividuals] */ + @Deprecated("use `list` instead") + @MustBeClosed + fun listIndividuals( + requestOptions: RequestOptions + ): CompletableFuture> = + listIndividuals(HrisDirectoryListIndividualsParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DirectoryServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DirectoryServiceAsyncImpl.kt index 00b8c0bb..9bc43a06 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DirectoryServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DirectoryServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,8 +11,9 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.HrisDirectoryListIndividualsPageAsync import com.tryfinch.api.models.HrisDirectoryListIndividualsParams import com.tryfinch.api.models.HrisDirectoryListPageAsync @@ -21,64 +23,106 @@ import java.util.concurrent.CompletableFuture class DirectoryServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : DirectoryServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: DirectoryServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): DirectoryServiceAsync.WithRawResponse = withRawResponse - /** Read company directory and organization structure */ override fun list( params: HrisDirectoryListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "directory") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - .let { HrisDirectoryListPageAsync.of(this, params, it) } - } - } + ): CompletableFuture = + // get /employer/directory + withRawResponse().list(params, requestOptions).thenApply { it.parse() } - private val listIndividualsHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Read company directory and organization structure */ @Deprecated("use `list` instead") override fun listIndividuals( params: HrisDirectoryListIndividualsParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "directory") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listIndividualsHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // get /employer/directory + withRawResponse().listIndividuals(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + DirectoryServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun list( + params: HrisDirectoryListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "directory") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisDirectoryListPageAsync.of( + DirectoryServiceAsyncImpl(clientOptions), + params, + it, + ) + } + } + } + } + + private val listIndividualsHandler: + Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + @Deprecated("use `list` instead") + override fun listIndividuals( + params: HrisDirectoryListIndividualsParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "directory") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { listIndividualsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisDirectoryListIndividualsPageAsync.of( + DirectoryServiceAsyncImpl(clientOptions), + params, + it, + ) + } } - .let { HrisDirectoryListIndividualsPageAsync.of(this, params, it) } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DocumentServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DocumentServiceAsync.kt index 59291b23..a25175a1 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DocumentServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DocumentServiceAsync.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.DocumentListResponse import com.tryfinch.api.models.DocumentRetreiveResponse import com.tryfinch.api.models.HrisDocumentListParams @@ -13,18 +13,28 @@ import java.util.concurrent.CompletableFuture interface DocumentServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** * **Beta:** This endpoint is in beta and may change. Retrieve a list of company-wide documents. */ - @JvmOverloads + fun list(): CompletableFuture = list(HrisDocumentListParams.none()) + + /** @see [list] */ fun list( params: HrisDocumentListParams = HrisDocumentListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** - * **Beta:** This endpoint is in beta and may change. Retrieve a list of company-wide documents. - */ + /** @see [list] */ + fun list( + params: HrisDocumentListParams = HrisDocumentListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see [list] */ fun list(requestOptions: RequestOptions): CompletableFuture = list(HrisDocumentListParams.none(), requestOptions) @@ -32,9 +42,64 @@ interface DocumentServiceAsync { * **Beta:** This endpoint is in beta and may change. Retrieve details of a specific document by * its ID. */ - @JvmOverloads + fun retreive(params: HrisDocumentRetreiveParams): CompletableFuture = + retreive(params, RequestOptions.none()) + + /** @see [retreive] */ fun retreive( params: HrisDocumentRetreiveParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [DocumentServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /employer/documents`, but is otherwise the same as + * [DocumentServiceAsync.list]. + */ + @MustBeClosed + fun list(): CompletableFuture> = + list(HrisDocumentListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisDocumentListParams = HrisDocumentListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisDocumentListParams = HrisDocumentListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(HrisDocumentListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /employer/documents/{document_id}`, but is otherwise + * the same as [DocumentServiceAsync.retreive]. + */ + @MustBeClosed + fun retreive( + params: HrisDocumentRetreiveParams + ): CompletableFuture> = + retreive(params, RequestOptions.none()) + + /** @see [retreive] */ + @MustBeClosed + fun retreive( + params: HrisDocumentRetreiveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DocumentServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DocumentServiceAsyncImpl.kt index a3faa516..7f6e4636 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DocumentServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/DocumentServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,8 +11,9 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.DocumentListResponse import com.tryfinch.api.models.DocumentRetreiveResponse import com.tryfinch.api.models.HrisDocumentListParams @@ -21,65 +23,89 @@ import java.util.concurrent.CompletableFuture class DocumentServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : DocumentServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: DocumentServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): DocumentServiceAsync.WithRawResponse = withRawResponse - /** - * **Beta:** This endpoint is in beta and may change. Retrieve a list of company-wide documents. - */ override fun list( params: HrisDocumentListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "documents") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } + ): CompletableFuture = + // get /employer/documents + withRawResponse().list(params, requestOptions).thenApply { it.parse() } - private val retreiveHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * **Beta:** This endpoint is in beta and may change. Retrieve details of a specific document by - * its ID. - */ override fun retreive( params: HrisDocumentRetreiveParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "documents", params.getPathParam(0)) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { retreiveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // get /employer/documents/{document_id} + withRawResponse().retreive(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + DocumentServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun list( + params: HrisDocumentListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "documents") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retreiveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retreive( + params: HrisDocumentRetreiveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "documents", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { retreiveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/EmploymentServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/EmploymentServiceAsync.kt index d12c27bc..9b0987cd 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/EmploymentServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/EmploymentServiceAsync.kt @@ -1,20 +1,54 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.HrisEmploymentRetrieveManyPageAsync import com.tryfinch.api.models.HrisEmploymentRetrieveManyParams import java.util.concurrent.CompletableFuture interface EmploymentServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Read individual employment and income data */ - @JvmOverloads + fun retrieveMany( + params: HrisEmploymentRetrieveManyParams + ): CompletableFuture = + retrieveMany(params, RequestOptions.none()) + + /** @see [retrieveMany] */ fun retrieveMany( params: HrisEmploymentRetrieveManyParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [EmploymentServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /employer/employment`, but is otherwise the same as + * [EmploymentServiceAsync.retrieveMany]. + */ + @MustBeClosed + fun retrieveMany( + params: HrisEmploymentRetrieveManyParams + ): CompletableFuture> = + retrieveMany(params, RequestOptions.none()) + + /** @see [retrieveMany] */ + @MustBeClosed + fun retrieveMany( + params: HrisEmploymentRetrieveManyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/EmploymentServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/EmploymentServiceAsyncImpl.kt index 07a11f84..c78b6123 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/EmploymentServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/EmploymentServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.HrisEmploymentRetrieveManyPageAsync import com.tryfinch.api.models.HrisEmploymentRetrieveManyParams import java.util.concurrent.CompletableFuture @@ -20,35 +22,60 @@ import java.util.concurrent.CompletableFuture class EmploymentServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : EmploymentServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: EmploymentServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val retrieveManyHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): EmploymentServiceAsync.WithRawResponse = withRawResponse - /** Read individual employment and income data */ override fun retrieveMany( params: HrisEmploymentRetrieveManyParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("employer", "employment") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { retrieveManyHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // post /employer/employment + withRawResponse().retrieveMany(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + EmploymentServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveManyHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retrieveMany( + params: HrisEmploymentRetrieveManyParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("employer", "employment") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { retrieveManyHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisEmploymentRetrieveManyPageAsync.of( + EmploymentServiceAsyncImpl(clientOptions), + params, + it, + ) + } } - .let { HrisEmploymentRetrieveManyPageAsync.of(this, params, it) } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/IndividualServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/IndividualServiceAsync.kt index c1e2218e..e51cd00b 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/IndividualServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/IndividualServiceAsync.kt @@ -1,26 +1,77 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.HrisIndividualRetrieveManyPageAsync import com.tryfinch.api.models.HrisIndividualRetrieveManyParams import java.util.concurrent.CompletableFuture interface IndividualServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Read individual data, excluding income and employment data */ - @JvmOverloads + fun retrieveMany(): CompletableFuture = + retrieveMany(HrisIndividualRetrieveManyParams.none()) + + /** @see [retrieveMany] */ fun retrieveMany( params: HrisIndividualRetrieveManyParams = HrisIndividualRetrieveManyParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** Read individual data, excluding income and employment data */ + /** @see [retrieveMany] */ + fun retrieveMany( + params: HrisIndividualRetrieveManyParams = HrisIndividualRetrieveManyParams.none() + ): CompletableFuture = + retrieveMany(params, RequestOptions.none()) + + /** @see [retrieveMany] */ fun retrieveMany( requestOptions: RequestOptions ): CompletableFuture = retrieveMany(HrisIndividualRetrieveManyParams.none(), requestOptions) + + /** + * A view of [IndividualServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /employer/individual`, but is otherwise the same as + * [IndividualServiceAsync.retrieveMany]. + */ + @MustBeClosed + fun retrieveMany(): + CompletableFuture> = + retrieveMany(HrisIndividualRetrieveManyParams.none()) + + /** @see [retrieveMany] */ + @MustBeClosed + fun retrieveMany( + params: HrisIndividualRetrieveManyParams = HrisIndividualRetrieveManyParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [retrieveMany] */ + @MustBeClosed + fun retrieveMany( + params: HrisIndividualRetrieveManyParams = HrisIndividualRetrieveManyParams.none() + ): CompletableFuture> = + retrieveMany(params, RequestOptions.none()) + + /** @see [retrieveMany] */ + @MustBeClosed + fun retrieveMany( + requestOptions: RequestOptions + ): CompletableFuture> = + retrieveMany(HrisIndividualRetrieveManyParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/IndividualServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/IndividualServiceAsyncImpl.kt index a901d00d..8b1f0eb0 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/IndividualServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/IndividualServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.HrisIndividualRetrieveManyPageAsync import com.tryfinch.api.models.HrisIndividualRetrieveManyParams import java.util.concurrent.CompletableFuture @@ -20,35 +22,60 @@ import java.util.concurrent.CompletableFuture class IndividualServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : IndividualServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: IndividualServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val retrieveManyHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): IndividualServiceAsync.WithRawResponse = withRawResponse - /** Read individual data, excluding income and employment data */ override fun retrieveMany( params: HrisIndividualRetrieveManyParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("employer", "individual") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { retrieveManyHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // post /employer/individual + withRawResponse().retrieveMany(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + IndividualServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveManyHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retrieveMany( + params: HrisIndividualRetrieveManyParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("employer", "individual") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { retrieveManyHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisIndividualRetrieveManyPageAsync.of( + IndividualServiceAsyncImpl(clientOptions), + params, + it, + ) + } } - .let { HrisIndividualRetrieveManyPageAsync.of(this, params, it) } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PayStatementServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PayStatementServiceAsync.kt index 6cb4e5d8..79077b3a 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PayStatementServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PayStatementServiceAsync.kt @@ -1,24 +1,58 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.HrisPayStatementRetrieveManyPageAsync import com.tryfinch.api.models.HrisPayStatementRetrieveManyParams import java.util.concurrent.CompletableFuture interface PayStatementServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** * Read detailed pay statements for each individual. * * Deduction and contribution types are supported by the payroll systems that supports Benefits. */ - @JvmOverloads + fun retrieveMany( + params: HrisPayStatementRetrieveManyParams + ): CompletableFuture = + retrieveMany(params, RequestOptions.none()) + + /** @see [retrieveMany] */ fun retrieveMany( params: HrisPayStatementRetrieveManyParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [PayStatementServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /employer/pay-statement`, but is otherwise the same + * as [PayStatementServiceAsync.retrieveMany]. + */ + @MustBeClosed + fun retrieveMany( + params: HrisPayStatementRetrieveManyParams + ): CompletableFuture> = + retrieveMany(params, RequestOptions.none()) + + /** @see [retrieveMany] */ + @MustBeClosed + fun retrieveMany( + params: HrisPayStatementRetrieveManyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PayStatementServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PayStatementServiceAsyncImpl.kt index 5b5ac320..3a2366f1 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PayStatementServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PayStatementServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.HrisPayStatementRetrieveManyPageAsync import com.tryfinch.api.models.HrisPayStatementRetrieveManyParams import java.util.concurrent.CompletableFuture @@ -20,39 +22,60 @@ import java.util.concurrent.CompletableFuture class PayStatementServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : PayStatementServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: PayStatementServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val retrieveManyHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): PayStatementServiceAsync.WithRawResponse = withRawResponse - /** - * Read detailed pay statements for each individual. - * - * Deduction and contribution types are supported by the payroll systems that supports Benefits. - */ override fun retrieveMany( params: HrisPayStatementRetrieveManyParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("employer", "pay-statement") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { retrieveManyHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // post /employer/pay-statement + withRawResponse().retrieveMany(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PayStatementServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveManyHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retrieveMany( + params: HrisPayStatementRetrieveManyParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("employer", "pay-statement") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { retrieveManyHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisPayStatementRetrieveManyPageAsync.of( + PayStatementServiceAsyncImpl(clientOptions), + params, + it, + ) + } } - .let { HrisPayStatementRetrieveManyPageAsync.of(this, params, it) } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PaymentServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PaymentServiceAsync.kt index 98dee989..f0d25be6 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PaymentServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PaymentServiceAsync.kt @@ -1,20 +1,51 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.HrisPaymentListPageAsync import com.tryfinch.api.models.HrisPaymentListParams import java.util.concurrent.CompletableFuture interface PaymentServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Read payroll and contractor related payments by the company. */ - @JvmOverloads + fun list(params: HrisPaymentListParams): CompletableFuture = + list(params, RequestOptions.none()) + + /** @see [list] */ fun list( params: HrisPaymentListParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [PaymentServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /employer/payment`, but is otherwise the same as + * [PaymentServiceAsync.list]. + */ + @MustBeClosed + fun list( + params: HrisPaymentListParams + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisPaymentListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PaymentServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PaymentServiceAsyncImpl.kt index db387453..fb986187 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PaymentServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/PaymentServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,8 +11,9 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.HrisPaymentListPageAsync import com.tryfinch.api.models.HrisPaymentListParams import com.tryfinch.api.models.Payment @@ -20,39 +22,58 @@ import java.util.concurrent.CompletableFuture class PaymentServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : PaymentServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: PaymentServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val listHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): PaymentServiceAsync.WithRawResponse = withRawResponse - /** Read payroll and contractor related payments by the company. */ override fun list( params: HrisPaymentListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "payment") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } - } - .let { - HrisPaymentListPageAsync.of( - this, - params, - HrisPaymentListPageAsync.Response.builder().items(it).build(), - ) + ): CompletableFuture = + // get /employer/payment + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PaymentServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun list( + params: HrisPaymentListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "payment") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + HrisPaymentListPageAsync.of( + PaymentServiceAsyncImpl(clientOptions), + params, + HrisPaymentListPageAsync.Response.builder().items(it).build(), + ) + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/benefits/IndividualServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/benefits/IndividualServiceAsync.kt index 62575fe9..989961fa 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/benefits/IndividualServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/benefits/IndividualServiceAsync.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.hris.benefits +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.HrisBenefitIndividualEnrolledIdsParams import com.tryfinch.api.models.HrisBenefitIndividualRetrieveManyBenefitsPageAsync import com.tryfinch.api.models.HrisBenefitIndividualRetrieveManyBenefitsParams @@ -15,24 +15,101 @@ import java.util.concurrent.CompletableFuture interface IndividualServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Lists individuals currently enrolled in a given deduction. */ - @JvmOverloads + fun enrolledIds( + params: HrisBenefitIndividualEnrolledIdsParams + ): CompletableFuture = enrolledIds(params, RequestOptions.none()) + + /** @see [enrolledIds] */ fun enrolledIds( params: HrisBenefitIndividualEnrolledIdsParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture /** Get enrollment information for the given individuals. */ - @JvmOverloads + fun retrieveManyBenefits( + params: HrisBenefitIndividualRetrieveManyBenefitsParams + ): CompletableFuture = + retrieveManyBenefits(params, RequestOptions.none()) + + /** @see [retrieveManyBenefits] */ fun retrieveManyBenefits( params: HrisBenefitIndividualRetrieveManyBenefitsParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture /** Unenroll individuals from a deduction or contribution */ - @JvmOverloads + fun unenrollMany( + params: HrisBenefitIndividualUnenrollManyParams + ): CompletableFuture = + unenrollMany(params, RequestOptions.none()) + + /** @see [unenrollMany] */ fun unenrollMany( params: HrisBenefitIndividualUnenrollManyParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [IndividualServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /employer/benefits/{benefit_id}/enrolled`, but is + * otherwise the same as [IndividualServiceAsync.enrolledIds]. + */ + @MustBeClosed + fun enrolledIds( + params: HrisBenefitIndividualEnrolledIdsParams + ): CompletableFuture> = + enrolledIds(params, RequestOptions.none()) + + /** @see [enrolledIds] */ + @MustBeClosed + fun enrolledIds( + params: HrisBenefitIndividualEnrolledIdsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /employer/benefits/{benefit_id}/individuals`, but is + * otherwise the same as [IndividualServiceAsync.retrieveManyBenefits]. + */ + @MustBeClosed + fun retrieveManyBenefits( + params: HrisBenefitIndividualRetrieveManyBenefitsParams + ): CompletableFuture> = + retrieveManyBenefits(params, RequestOptions.none()) + + /** @see [retrieveManyBenefits] */ + @MustBeClosed + fun retrieveManyBenefits( + params: HrisBenefitIndividualRetrieveManyBenefitsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `delete /employer/benefits/{benefit_id}/individuals`, but + * is otherwise the same as [IndividualServiceAsync.unenrollMany]. + */ + @MustBeClosed + fun unenrollMany( + params: HrisBenefitIndividualUnenrollManyParams + ): CompletableFuture> = + unenrollMany(params, RequestOptions.none()) + + /** @see [unenrollMany] */ + @MustBeClosed + fun unenrollMany( + params: HrisBenefitIndividualUnenrollManyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/benefits/IndividualServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/benefits/IndividualServiceAsyncImpl.kt index db7f5262..3c10a2e7 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/benefits/IndividualServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/benefits/IndividualServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.hris.benefits import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.HrisBenefitIndividualEnrolledIdsParams import com.tryfinch.api.models.HrisBenefitIndividualRetrieveManyBenefitsPageAsync import com.tryfinch.api.models.HrisBenefitIndividualRetrieveManyBenefitsParams @@ -26,108 +28,146 @@ import java.util.concurrent.CompletableFuture class IndividualServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : IndividualServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: IndividualServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val enrolledIdsHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): IndividualServiceAsync.WithRawResponse = withRawResponse - /** Lists individuals currently enrolled in a given deduction. */ override fun enrolledIds( params: HrisBenefitIndividualEnrolledIdsParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "benefits", params.getPathParam(0), "enrolled") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { enrolledIdsHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } + ): CompletableFuture = + // get /employer/benefits/{benefit_id}/enrolled + withRawResponse().enrolledIds(params, requestOptions).thenApply { it.parse() } - private val retrieveManyBenefitsHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Get enrollment information for the given individuals. */ override fun retrieveManyBenefits( params: HrisBenefitIndividualRetrieveManyBenefitsParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "benefits", params.getPathParam(0), "individuals") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { retrieveManyBenefitsHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } - } - .let { - HrisBenefitIndividualRetrieveManyBenefitsPageAsync.of( - this, - params, - HrisBenefitIndividualRetrieveManyBenefitsPageAsync.Response.builder() - .items(it) - .build(), - ) - } - } - } + ): CompletableFuture = + // get /employer/benefits/{benefit_id}/individuals + withRawResponse().retrieveManyBenefits(params, requestOptions).thenApply { it.parse() } - private val unenrollManyHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Unenroll individuals from a deduction or contribution */ override fun unenrollMany( params: HrisBenefitIndividualUnenrollManyParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("employer", "benefits", params.getPathParam(0), "individuals") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { unenrollManyHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } + ): CompletableFuture = + // delete /employer/benefits/{benefit_id}/individuals + withRawResponse().unenrollMany(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + IndividualServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val enrolledIdsHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun enrolledIds( + params: HrisBenefitIndividualEnrolledIdsParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "benefits", params._pathParam(0), "enrolled") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { enrolledIdsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveManyBenefitsHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retrieveManyBenefits( + params: HrisBenefitIndividualRetrieveManyBenefitsParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "benefits", params._pathParam(0), "individuals") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { retrieveManyBenefitsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + HrisBenefitIndividualRetrieveManyBenefitsPageAsync.of( + IndividualServiceAsyncImpl(clientOptions), + params, + HrisBenefitIndividualRetrieveManyBenefitsPageAsync.Response + .builder() + .items(it) + .build(), + ) + } } - .let { - HrisBenefitIndividualUnenrollManyPageAsync.of( - this, - params, - HrisBenefitIndividualUnenrollManyPageAsync.Response.builder() - .items(it) - .build(), - ) + } + } + + private val unenrollManyHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun unenrollMany( + params: HrisBenefitIndividualUnenrollManyParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .addPathSegments("employer", "benefits", params._pathParam(0), "individuals") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { unenrollManyHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + HrisBenefitIndividualUnenrollManyPageAsync.of( + IndividualServiceAsyncImpl(clientOptions), + params, + HrisBenefitIndividualUnenrollManyPageAsync.Response.builder() + .items(it) + .build(), + ) + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/company/PayStatementItemServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/company/PayStatementItemServiceAsync.kt new file mode 100644 index 00000000..a0fdb11b --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/company/PayStatementItemServiceAsync.kt @@ -0,0 +1,88 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.services.async.hris.company + +import com.google.errorprone.annotations.MustBeClosed +import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.models.HrisCompanyPayStatementItemListPageAsync +import com.tryfinch.api.models.HrisCompanyPayStatementItemListParams +import com.tryfinch.api.services.async.hris.company.payStatementItem.RuleServiceAsync +import java.util.concurrent.CompletableFuture + +interface PayStatementItemServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + fun rules(): RuleServiceAsync + + /** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Retrieve a list of detailed pay statement items for the access + * token's connection account. + */ + fun list(): CompletableFuture = + list(HrisCompanyPayStatementItemListParams.none()) + + /** @see [list] */ + fun list( + params: HrisCompanyPayStatementItemListParams = + HrisCompanyPayStatementItemListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see [list] */ + fun list( + params: HrisCompanyPayStatementItemListParams = HrisCompanyPayStatementItemListParams.none() + ): CompletableFuture = + list(params, RequestOptions.none()) + + /** @see [list] */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture = + list(HrisCompanyPayStatementItemListParams.none(), requestOptions) + + /** + * A view of [PayStatementItemServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + fun rules(): RuleServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /employer/pay-statement-item`, but is otherwise the + * same as [PayStatementItemServiceAsync.list]. + */ + @MustBeClosed + fun list(): CompletableFuture> = + list(HrisCompanyPayStatementItemListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisCompanyPayStatementItemListParams = + HrisCompanyPayStatementItemListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisCompanyPayStatementItemListParams = + HrisCompanyPayStatementItemListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(HrisCompanyPayStatementItemListParams.none(), requestOptions) + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/company/PayStatementItemServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/company/PayStatementItemServiceAsyncImpl.kt new file mode 100644 index 00000000..fd4b52bf --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/company/PayStatementItemServiceAsyncImpl.kt @@ -0,0 +1,91 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.services.async.hris.company + +import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.handlers.errorHandler +import com.tryfinch.api.core.handlers.jsonHandler +import com.tryfinch.api.core.handlers.withErrorHandler +import com.tryfinch.api.core.http.HttpMethod +import com.tryfinch.api.core.http.HttpRequest +import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable +import com.tryfinch.api.core.prepareAsync +import com.tryfinch.api.models.HrisCompanyPayStatementItemListPageAsync +import com.tryfinch.api.models.HrisCompanyPayStatementItemListParams +import com.tryfinch.api.services.async.hris.company.payStatementItem.RuleServiceAsync +import com.tryfinch.api.services.async.hris.company.payStatementItem.RuleServiceAsyncImpl +import java.util.concurrent.CompletableFuture + +class PayStatementItemServiceAsyncImpl +internal constructor(private val clientOptions: ClientOptions) : PayStatementItemServiceAsync { + + private val withRawResponse: PayStatementItemServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val rules: RuleServiceAsync by lazy { RuleServiceAsyncImpl(clientOptions) } + + override fun withRawResponse(): PayStatementItemServiceAsync.WithRawResponse = withRawResponse + + override fun rules(): RuleServiceAsync = rules + + override fun list( + params: HrisCompanyPayStatementItemListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /employer/pay-statement-item + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PayStatementItemServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val rules: RuleServiceAsync.WithRawResponse by lazy { + RuleServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun rules(): RuleServiceAsync.WithRawResponse = rules + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun list( + params: HrisCompanyPayStatementItemListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "pay-statement-item") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisCompanyPayStatementItemListPageAsync.of( + PayStatementItemServiceAsyncImpl(clientOptions), + params, + it, + ) + } + } + } + } + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/company/payStatementItem/RuleServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/company/payStatementItem/RuleServiceAsync.kt new file mode 100644 index 00000000..e19add98 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/company/payStatementItem/RuleServiceAsync.kt @@ -0,0 +1,207 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.services.async.hris.company.payStatementItem + +import com.google.errorprone.annotations.MustBeClosed +import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleCreateParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleDeleteParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleListPageAsync +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleListParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleUpdateParams +import com.tryfinch.api.models.RuleCreateResponse +import com.tryfinch.api.models.RuleDeleteResponse +import com.tryfinch.api.models.RuleUpdateResponse +import java.util.concurrent.CompletableFuture + +interface RuleServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Custom rules can be created to associate specific attributes to + * pay statement items depending on the use case. For example, pay statement items that meet + * certain conditions can be labeled as a pre-tax 401k. This metadata can be retrieved where pay + * statement item information is available. + */ + fun create(): CompletableFuture = + create(HrisCompanyPayStatementItemRuleCreateParams.none()) + + /** @see [create] */ + fun create( + params: HrisCompanyPayStatementItemRuleCreateParams = + HrisCompanyPayStatementItemRuleCreateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see [create] */ + fun create( + params: HrisCompanyPayStatementItemRuleCreateParams = + HrisCompanyPayStatementItemRuleCreateParams.none() + ): CompletableFuture = create(params, RequestOptions.none()) + + /** @see [create] */ + fun create(requestOptions: RequestOptions): CompletableFuture = + create(HrisCompanyPayStatementItemRuleCreateParams.none(), requestOptions) + + /** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Update a rule for a pay statement item. + */ + fun update( + params: HrisCompanyPayStatementItemRuleUpdateParams + ): CompletableFuture = update(params, RequestOptions.none()) + + /** @see [update] */ + fun update( + params: HrisCompanyPayStatementItemRuleUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon List all rules of a connection account. + */ + fun list(): CompletableFuture = + list(HrisCompanyPayStatementItemRuleListParams.none()) + + /** @see [list] */ + fun list( + params: HrisCompanyPayStatementItemRuleListParams = + HrisCompanyPayStatementItemRuleListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see [list] */ + fun list( + params: HrisCompanyPayStatementItemRuleListParams = + HrisCompanyPayStatementItemRuleListParams.none() + ): CompletableFuture = + list(params, RequestOptions.none()) + + /** @see [list] */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture = + list(HrisCompanyPayStatementItemRuleListParams.none(), requestOptions) + + /** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Delete a rule for a pay statement item. + */ + fun delete( + params: HrisCompanyPayStatementItemRuleDeleteParams + ): CompletableFuture = delete(params, RequestOptions.none()) + + /** @see [delete] */ + fun delete( + params: HrisCompanyPayStatementItemRuleDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** A view of [RuleServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /employer/pay-statement-item/rule`, but is + * otherwise the same as [RuleServiceAsync.create]. + */ + @MustBeClosed + fun create(): CompletableFuture> = + create(HrisCompanyPayStatementItemRuleCreateParams.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: HrisCompanyPayStatementItemRuleCreateParams = + HrisCompanyPayStatementItemRuleCreateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [create] */ + @MustBeClosed + fun create( + params: HrisCompanyPayStatementItemRuleCreateParams = + HrisCompanyPayStatementItemRuleCreateParams.none() + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + requestOptions: RequestOptions + ): CompletableFuture> = + create(HrisCompanyPayStatementItemRuleCreateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /employer/pay-statement-item/rule/{rule_id}`, but is + * otherwise the same as [RuleServiceAsync.update]. + */ + @MustBeClosed + fun update( + params: HrisCompanyPayStatementItemRuleUpdateParams + ): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: HrisCompanyPayStatementItemRuleUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /employer/pay-statement-item/rule`, but is otherwise + * the same as [RuleServiceAsync.list]. + */ + @MustBeClosed + fun list(): + CompletableFuture> = + list(HrisCompanyPayStatementItemRuleListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisCompanyPayStatementItemRuleListParams = + HrisCompanyPayStatementItemRuleListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisCompanyPayStatementItemRuleListParams = + HrisCompanyPayStatementItemRuleListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(HrisCompanyPayStatementItemRuleListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /employer/pay-statement-item/rule/{rule_id}`, but + * is otherwise the same as [RuleServiceAsync.delete]. + */ + @MustBeClosed + fun delete( + params: HrisCompanyPayStatementItemRuleDeleteParams + ): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see [delete] */ + @MustBeClosed + fun delete( + params: HrisCompanyPayStatementItemRuleDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/company/payStatementItem/RuleServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/company/payStatementItem/RuleServiceAsyncImpl.kt new file mode 100644 index 00000000..1f3cb3b0 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/hris/company/payStatementItem/RuleServiceAsyncImpl.kt @@ -0,0 +1,199 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.services.async.hris.company.payStatementItem + +import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.handlers.errorHandler +import com.tryfinch.api.core.handlers.jsonHandler +import com.tryfinch.api.core.handlers.withErrorHandler +import com.tryfinch.api.core.http.HttpMethod +import com.tryfinch.api.core.http.HttpRequest +import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable +import com.tryfinch.api.core.prepareAsync +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleCreateParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleDeleteParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleListPageAsync +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleListParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleUpdateParams +import com.tryfinch.api.models.RuleCreateResponse +import com.tryfinch.api.models.RuleDeleteResponse +import com.tryfinch.api.models.RuleUpdateResponse +import java.util.concurrent.CompletableFuture + +class RuleServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + RuleServiceAsync { + + private val withRawResponse: RuleServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): RuleServiceAsync.WithRawResponse = withRawResponse + + override fun create( + params: HrisCompanyPayStatementItemRuleCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /employer/pay-statement-item/rule + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: HrisCompanyPayStatementItemRuleUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /employer/pay-statement-item/rule/{rule_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: HrisCompanyPayStatementItemRuleListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /employer/pay-statement-item/rule + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: HrisCompanyPayStatementItemRuleDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /employer/pay-statement-item/rule/{rule_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + RuleServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun create( + params: HrisCompanyPayStatementItemRuleCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("employer", "pay-statement-item", "rule") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun update( + params: HrisCompanyPayStatementItemRuleUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .addPathSegments("employer", "pay-statement-item", "rule", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler( + clientOptions.jsonMapper + ) + .withErrorHandler(errorHandler) + + override fun list( + params: HrisCompanyPayStatementItemRuleListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "pay-statement-item", "rule") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisCompanyPayStatementItemRuleListPageAsync.of( + RuleServiceAsyncImpl(clientOptions), + params, + it, + ) + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun delete( + params: HrisCompanyPayStatementItemRuleDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .addPathSegments("employer", "pay-statement-item", "rule", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/AutomatedServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/AutomatedServiceAsync.kt index 3d03563b..374f8672 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/AutomatedServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/AutomatedServiceAsync.kt @@ -1,20 +1,25 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.jobs +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.AutomatedAsyncJob import com.tryfinch.api.models.AutomatedCreateResponse +import com.tryfinch.api.models.AutomatedListResponse import com.tryfinch.api.models.JobAutomatedCreateParams -import com.tryfinch.api.models.JobAutomatedListPageAsync import com.tryfinch.api.models.JobAutomatedListParams import com.tryfinch.api.models.JobAutomatedRetrieveParams import java.util.concurrent.CompletableFuture interface AutomatedServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** * Enqueue an automated job. * @@ -30,32 +35,29 @@ interface AutomatedServiceAsync { * This endpoint is available for _Scale_ tier customers as an add-on. To request access to this * endpoint, please contact your Finch account manager. */ - @JvmOverloads + fun create(): CompletableFuture = + create(JobAutomatedCreateParams.none()) + + /** @see [create] */ fun create( params: JobAutomatedCreateParams = JobAutomatedCreateParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** - * Enqueue an automated job. - * - * `data_sync_all`: Enqueue a job to re-sync all data for a connection. `data_sync_all` has a - * concurrency limit of 1 job at a time per connection. This means that if this endpoint is - * called while a job is already in progress for this connection, Finch will return the `job_id` - * of the job that is currently in progress. Finch allows a fixed window rate limit of 1 forced - * refresh per hour per connection. - * - * `w4_form_employee_sync`: Enqueues a job for sync W-4 data for a particular individual, - * identified by `individual_id`. This feature is currently in beta. - * - * This endpoint is available for _Scale_ tier customers as an add-on. To request access to this - * endpoint, please contact your Finch account manager. - */ + /** @see [create] */ + fun create( + params: JobAutomatedCreateParams = JobAutomatedCreateParams.none() + ): CompletableFuture = create(params, RequestOptions.none()) + + /** @see [create] */ fun create(requestOptions: RequestOptions): CompletableFuture = create(JobAutomatedCreateParams.none(), requestOptions) /** Get an automated job by `job_id`. */ - @JvmOverloads + fun retrieve(params: JobAutomatedRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ fun retrieve( params: JobAutomatedRetrieveParams, requestOptions: RequestOptions = RequestOptions.none(), @@ -66,17 +68,101 @@ interface AutomatedServiceAsync { * sorted in descending order by submission time. For scheduled jobs such as data syncs, only * the next scheduled job is shown. */ - @JvmOverloads + fun list(): CompletableFuture = list(JobAutomatedListParams.none()) + + /** @see [list] */ fun list( params: JobAutomatedListParams = JobAutomatedListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture + ): CompletableFuture + + /** @see [list] */ + fun list( + params: JobAutomatedListParams = JobAutomatedListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see [list] */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(JobAutomatedListParams.none(), requestOptions) /** - * Get all automated jobs. Automated jobs are completed by a machine. By default, jobs are - * sorted in descending order by submission time. For scheduled jobs such as data syncs, only - * the next scheduled job is shown. + * A view of [AutomatedServiceAsync] that provides access to raw HTTP responses for each method. */ - fun list(requestOptions: RequestOptions): CompletableFuture = - list(JobAutomatedListParams.none(), requestOptions) + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /jobs/automated`, but is otherwise the same as + * [AutomatedServiceAsync.create]. + */ + @MustBeClosed + fun create(): CompletableFuture> = + create(JobAutomatedCreateParams.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: JobAutomatedCreateParams = JobAutomatedCreateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [create] */ + @MustBeClosed + fun create( + params: JobAutomatedCreateParams = JobAutomatedCreateParams.none() + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + requestOptions: RequestOptions + ): CompletableFuture> = + create(JobAutomatedCreateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /jobs/automated/{job_id}`, but is otherwise the same + * as [AutomatedServiceAsync.retrieve]. + */ + @MustBeClosed + fun retrieve( + params: JobAutomatedRetrieveParams + ): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: JobAutomatedRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /jobs/automated`, but is otherwise the same as + * [AutomatedServiceAsync.list]. + */ + @MustBeClosed + fun list(): CompletableFuture> = + list(JobAutomatedListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: JobAutomatedListParams = JobAutomatedListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [list] */ + @MustBeClosed + fun list( + params: JobAutomatedListParams = JobAutomatedListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(JobAutomatedListParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/AutomatedServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/AutomatedServiceAsyncImpl.kt index 9a621fc9..486c207e 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/AutomatedServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/AutomatedServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.jobs import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,13 +11,14 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.AutomatedAsyncJob import com.tryfinch.api.models.AutomatedCreateResponse +import com.tryfinch.api.models.AutomatedListResponse import com.tryfinch.api.models.JobAutomatedCreateParams -import com.tryfinch.api.models.JobAutomatedListPageAsync import com.tryfinch.api.models.JobAutomatedListParams import com.tryfinch.api.models.JobAutomatedRetrieveParams import java.util.concurrent.CompletableFuture @@ -24,108 +26,126 @@ import java.util.concurrent.CompletableFuture class AutomatedServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : AutomatedServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) - - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * Enqueue an automated job. - * - * `data_sync_all`: Enqueue a job to re-sync all data for a connection. `data_sync_all` has a - * concurrency limit of 1 job at a time per connection. This means that if this endpoint is - * called while a job is already in progress for this connection, Finch will return the `job_id` - * of the job that is currently in progress. Finch allows a fixed window rate limit of 1 forced - * refresh per hour per connection. - * - * `w4_form_employee_sync`: Enqueues a job for sync W-4 data for a particular individual, - * identified by `individual_id`. This feature is currently in beta. - * - * This endpoint is available for _Scale_ tier customers as an add-on. To request access to this - * endpoint, please contact your Finch account manager. - */ + private val withRawResponse: AutomatedServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): AutomatedServiceAsync.WithRawResponse = withRawResponse + override fun create( params: JobAutomatedCreateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("jobs", "automated") - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } + ): CompletableFuture = + // post /jobs/automated + withRawResponse().create(params, requestOptions).thenApply { it.parse() } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Get an automated job by `job_id`. */ override fun retrieve( params: JobAutomatedRetrieveParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("jobs", "automated", params.getPathParam(0)) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { retrieveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } + ): CompletableFuture = + // get /jobs/automated/{job_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * Get all automated jobs. Automated jobs are completed by a machine. By default, jobs are - * sorted in descending order by submission time. For scheduled jobs such as data syncs, only - * the next scheduled job is shown. - */ override fun list( params: JobAutomatedListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("jobs", "automated") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // get /jobs/automated + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AutomatedServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: JobAutomatedCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("jobs", "automated") + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun retrieve( + params: JobAutomatedRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("jobs", "automated", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun list( + params: JobAutomatedListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("jobs", "automated") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - .let { JobAutomatedListPageAsync.of(this, params, it) } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/ManualServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/ManualServiceAsync.kt index b3b9e674..0d51c731 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/ManualServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/ManualServiceAsync.kt @@ -1,23 +1,54 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.jobs +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.JobManualRetrieveParams import com.tryfinch.api.models.ManualAsyncJob import java.util.concurrent.CompletableFuture interface ManualServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** * Get a manual job by `job_id`. Manual jobs are completed by a human and include Assisted * Benefits jobs. */ - @JvmOverloads + fun retrieve(params: JobManualRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ fun retrieve( params: JobManualRetrieveParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [ManualServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /jobs/manual/{job_id}`, but is otherwise the same as + * [ManualServiceAsync.retrieve]. + */ + @MustBeClosed + fun retrieve( + params: JobManualRetrieveParams + ): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: JobManualRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/ManualServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/ManualServiceAsyncImpl.kt index 4b05c57a..29425dfd 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/ManualServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/jobs/ManualServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.jobs import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,8 +11,9 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.JobManualRetrieveParams import com.tryfinch.api.models.ManualAsyncJob import java.util.concurrent.CompletableFuture @@ -19,35 +21,51 @@ import java.util.concurrent.CompletableFuture class ManualServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : ManualServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ManualServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): ManualServiceAsync.WithRawResponse = withRawResponse - /** - * Get a manual job by `job_id`. Manual jobs are completed by a human and include Assisted - * Benefits jobs. - */ override fun retrieve( params: JobManualRetrieveParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("jobs", "manual", params.getPathParam(0)) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { retrieveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // get /jobs/manual/{job_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ManualServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun retrieve( + params: JobManualRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("jobs", "manual", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/payroll/PayGroupServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/payroll/PayGroupServiceAsync.kt index bc144858..837276f5 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/payroll/PayGroupServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/payroll/PayGroupServiceAsync.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.payroll +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.PayGroupRetrieveResponse import com.tryfinch.api.models.PayrollPayGroupListPageAsync import com.tryfinch.api.models.PayrollPayGroupListParams @@ -13,21 +13,90 @@ import java.util.concurrent.CompletableFuture interface PayGroupServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Read information from a single pay group */ - @JvmOverloads + fun retrieve( + params: PayrollPayGroupRetrieveParams + ): CompletableFuture = retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ fun retrieve( params: PayrollPayGroupRetrieveParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture /** Read company pay groups and frequencies */ - @JvmOverloads + fun list(): CompletableFuture = + list(PayrollPayGroupListParams.none()) + + /** @see [list] */ fun list( params: PayrollPayGroupListParams = PayrollPayGroupListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** Read company pay groups and frequencies */ + /** @see [list] */ + fun list( + params: PayrollPayGroupListParams = PayrollPayGroupListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see [list] */ fun list(requestOptions: RequestOptions): CompletableFuture = list(PayrollPayGroupListParams.none(), requestOptions) + + /** + * A view of [PayGroupServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /employer/pay-groups/{pay_group_id}`, but is + * otherwise the same as [PayGroupServiceAsync.retrieve]. + */ + @MustBeClosed + fun retrieve( + params: PayrollPayGroupRetrieveParams + ): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: PayrollPayGroupRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /employer/pay-groups`, but is otherwise the same as + * [PayGroupServiceAsync.list]. + */ + @MustBeClosed + fun list(): CompletableFuture> = + list(PayrollPayGroupListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: PayrollPayGroupListParams = PayrollPayGroupListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [list] */ + @MustBeClosed + fun list( + params: PayrollPayGroupListParams = PayrollPayGroupListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(PayrollPayGroupListParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/payroll/PayGroupServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/payroll/PayGroupServiceAsyncImpl.kt index c9fa6c1a..e293c454 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/payroll/PayGroupServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/payroll/PayGroupServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.payroll import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,8 +11,9 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.PayGroupListResponse import com.tryfinch.api.models.PayGroupRetrieveResponse import com.tryfinch.api.models.PayrollPayGroupListPageAsync @@ -22,68 +24,98 @@ import java.util.concurrent.CompletableFuture class PayGroupServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : PayGroupServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: PayGroupServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): PayGroupServiceAsync.WithRawResponse = withRawResponse - /** Read information from a single pay group */ override fun retrieve( params: PayrollPayGroupRetrieveParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "pay-groups", params.getPathParam(0)) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { retrieveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } + ): CompletableFuture = + // get /employer/pay-groups/{pay_group_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } - private val listHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Read company pay groups and frequencies */ override fun list( params: PayrollPayGroupListParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "pay-groups") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } + ): CompletableFuture = + // get /employer/pay-groups + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PayGroupServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retrieve( + params: PayrollPayGroupRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "pay-groups", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - .let { - PayrollPayGroupListPageAsync.of( - this, - params, - PayrollPayGroupListPageAsync.Response.builder().items(it).build(), - ) + } + } + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun list( + params: PayrollPayGroupListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "pay-groups") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + PayrollPayGroupListPageAsync.of( + PayGroupServiceAsyncImpl(clientOptions), + params, + PayrollPayGroupListPageAsync.Response.builder() + .items(it) + .build(), + ) + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/CompanyServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/CompanyServiceAsync.kt index 09dc9208..5b946b43 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/CompanyServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/CompanyServiceAsync.kt @@ -1,20 +1,51 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.sandbox +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.CompanyUpdateResponse import com.tryfinch.api.models.SandboxCompanyUpdateParams import java.util.concurrent.CompletableFuture interface CompanyServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Update a sandbox company's data */ - @JvmOverloads + fun update(params: SandboxCompanyUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see [update] */ fun update( params: SandboxCompanyUpdateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [CompanyServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `put /sandbox/company`, but is otherwise the same as + * [CompanyServiceAsync.update]. + */ + @MustBeClosed + fun update( + params: SandboxCompanyUpdateParams + ): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: SandboxCompanyUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/CompanyServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/CompanyServiceAsyncImpl.kt index 4ca29904..bb6bd71a 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/CompanyServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/CompanyServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.sandbox import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.CompanyUpdateResponse import com.tryfinch.api.models.SandboxCompanyUpdateParams import java.util.concurrent.CompletableFuture @@ -20,33 +22,53 @@ import java.util.concurrent.CompletableFuture class CompanyServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : CompanyServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: CompanyServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): CompanyServiceAsync.WithRawResponse = withRawResponse - /** Update a sandbox company's data */ override fun update( params: SandboxCompanyUpdateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("sandbox", "company") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // put /sandbox/company + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + CompanyServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun update( + params: SandboxCompanyUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .addPathSegments("sandbox", "company") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/ConnectionServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/ConnectionServiceAsync.kt index 02284513..77f7287e 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/ConnectionServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/ConnectionServiceAsync.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.sandbox +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.ConnectionCreateResponse import com.tryfinch.api.models.SandboxConnectionCreateParams import com.tryfinch.api.services.async.sandbox.connections.AccountServiceAsync @@ -12,12 +12,46 @@ import java.util.concurrent.CompletableFuture interface ConnectionServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun accounts(): AccountServiceAsync /** Create a new connection (new company/provider pair) with a new account */ - @JvmOverloads + fun create(params: SandboxConnectionCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see [create] */ fun create( params: SandboxConnectionCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [ConnectionServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + fun accounts(): AccountServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /sandbox/connections`, but is otherwise the same as + * [ConnectionServiceAsync.create]. + */ + @MustBeClosed + fun create( + params: SandboxConnectionCreateParams + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxConnectionCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/ConnectionServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/ConnectionServiceAsyncImpl.kt index aecc772e..25170227 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/ConnectionServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/ConnectionServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.sandbox import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.ConnectionCreateResponse import com.tryfinch.api.models.SandboxConnectionCreateParams import com.tryfinch.api.services.async.sandbox.connections.AccountServiceAsync @@ -22,38 +24,63 @@ import java.util.concurrent.CompletableFuture class ConnectionServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : ConnectionServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ConnectionServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } private val accounts: AccountServiceAsync by lazy { AccountServiceAsyncImpl(clientOptions) } - override fun accounts(): AccountServiceAsync = accounts + override fun withRawResponse(): ConnectionServiceAsync.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun accounts(): AccountServiceAsync = accounts - /** Create a new connection (new company/provider pair) with a new account */ override fun create( params: SandboxConnectionCreateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("sandbox", "connections") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // post /sandbox/connections + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ConnectionServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val accounts: AccountServiceAsync.WithRawResponse by lazy { + AccountServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun accounts(): AccountServiceAsync.WithRawResponse = accounts + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: SandboxConnectionCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("sandbox", "connections") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/DirectoryServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/DirectoryServiceAsync.kt index 8155d37a..66f7b336 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/DirectoryServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/DirectoryServiceAsync.kt @@ -1,24 +1,72 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.sandbox -import com.tryfinch.api.core.JsonValue +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.models.DirectoryCreateResponse import com.tryfinch.api.models.SandboxDirectoryCreateParams import java.util.concurrent.CompletableFuture interface DirectoryServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Add new individuals to a sandbox company */ - @JvmOverloads + fun create(): CompletableFuture> = + create(SandboxDirectoryCreateParams.none()) + + /** @see [create] */ fun create( params: SandboxDirectoryCreateParams = SandboxDirectoryCreateParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): CompletableFuture> + ): CompletableFuture> - /** Add new individuals to a sandbox company */ - fun create(requestOptions: RequestOptions): CompletableFuture> = + /** @see [create] */ + fun create( + params: SandboxDirectoryCreateParams = SandboxDirectoryCreateParams.none() + ): CompletableFuture> = create(params, RequestOptions.none()) + + /** @see [create] */ + fun create(requestOptions: RequestOptions): CompletableFuture> = create(SandboxDirectoryCreateParams.none(), requestOptions) + + /** + * A view of [DirectoryServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /sandbox/directory`, but is otherwise the same as + * [DirectoryServiceAsync.create]. + */ + @MustBeClosed + fun create(): CompletableFuture>> = + create(SandboxDirectoryCreateParams.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxDirectoryCreateParams = SandboxDirectoryCreateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture>> + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxDirectoryCreateParams = SandboxDirectoryCreateParams.none() + ): CompletableFuture>> = + create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + requestOptions: RequestOptions + ): CompletableFuture>> = + create(SandboxDirectoryCreateParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/DirectoryServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/DirectoryServiceAsyncImpl.kt index f65ae934..6da02916 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/DirectoryServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/DirectoryServiceAsyncImpl.kt @@ -11,34 +11,64 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError +import com.tryfinch.api.models.DirectoryCreateResponse import com.tryfinch.api.models.SandboxDirectoryCreateParams import java.util.concurrent.CompletableFuture class DirectoryServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : DirectoryServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: DirectoryServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val createHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): DirectoryServiceAsync.WithRawResponse = withRawResponse - /** Add new individuals to a sandbox company */ override fun create( params: SandboxDirectoryCreateParams, requestOptions: RequestOptions, - ): CompletableFuture> { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("sandbox", "directory") - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> response.use { createHandler.handle(it) } } + ): CompletableFuture> = + // post /sandbox/directory + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + DirectoryServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: SandboxDirectoryCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture>> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("sandbox", "directory") + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/EmploymentServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/EmploymentServiceAsync.kt index 00219b33..ad8fabfa 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/EmploymentServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/EmploymentServiceAsync.kt @@ -1,20 +1,52 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.sandbox +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.EmploymentUpdateResponse import com.tryfinch.api.models.SandboxEmploymentUpdateParams import java.util.concurrent.CompletableFuture interface EmploymentServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Update sandbox employment */ - @JvmOverloads + fun update(params: SandboxEmploymentUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see [update] */ fun update( params: SandboxEmploymentUpdateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [EmploymentServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `put /sandbox/employment/{individual_id}`, but is + * otherwise the same as [EmploymentServiceAsync.update]. + */ + @MustBeClosed + fun update( + params: SandboxEmploymentUpdateParams + ): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: SandboxEmploymentUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/EmploymentServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/EmploymentServiceAsyncImpl.kt index 11baffe9..212d7652 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/EmploymentServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/EmploymentServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.sandbox import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.EmploymentUpdateResponse import com.tryfinch.api.models.SandboxEmploymentUpdateParams import java.util.concurrent.CompletableFuture @@ -20,34 +22,53 @@ import java.util.concurrent.CompletableFuture class EmploymentServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : EmploymentServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: EmploymentServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): EmploymentServiceAsync.WithRawResponse = withRawResponse - /** Update sandbox employment */ override fun update( params: SandboxEmploymentUpdateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("sandbox", "employment", params.getPathParam(0)) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // put /sandbox/employment/{individual_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + EmploymentServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun update( + params: SandboxEmploymentUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .addPathSegments("sandbox", "employment", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/IndividualServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/IndividualServiceAsync.kt index 81695b1c..47d38c4e 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/IndividualServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/IndividualServiceAsync.kt @@ -1,20 +1,52 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.sandbox +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.IndividualUpdateResponse import com.tryfinch.api.models.SandboxIndividualUpdateParams import java.util.concurrent.CompletableFuture interface IndividualServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Update sandbox individual */ - @JvmOverloads + fun update(params: SandboxIndividualUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see [update] */ fun update( params: SandboxIndividualUpdateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [IndividualServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `put /sandbox/individual/{individual_id}`, but is + * otherwise the same as [IndividualServiceAsync.update]. + */ + @MustBeClosed + fun update( + params: SandboxIndividualUpdateParams + ): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: SandboxIndividualUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/IndividualServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/IndividualServiceAsyncImpl.kt index d194f2c1..7cdca716 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/IndividualServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/IndividualServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.sandbox import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.IndividualUpdateResponse import com.tryfinch.api.models.SandboxIndividualUpdateParams import java.util.concurrent.CompletableFuture @@ -20,34 +22,53 @@ import java.util.concurrent.CompletableFuture class IndividualServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : IndividualServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: IndividualServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): IndividualServiceAsync.WithRawResponse = withRawResponse - /** Update sandbox individual */ override fun update( params: SandboxIndividualUpdateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("sandbox", "individual", params.getPathParam(0)) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // put /sandbox/individual/{individual_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + IndividualServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun update( + params: SandboxIndividualUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .addPathSegments("sandbox", "individual", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/JobServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/JobServiceAsync.kt index 56612e5b..e5cb1480 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/JobServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/JobServiceAsync.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.sandbox +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.JobCreateResponse import com.tryfinch.api.models.SandboxJobCreateParams import com.tryfinch.api.services.async.sandbox.jobs.ConfigurationServiceAsync @@ -12,12 +12,43 @@ import java.util.concurrent.CompletableFuture interface JobServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun configuration(): ConfigurationServiceAsync /** Enqueue a new sandbox job */ - @JvmOverloads + fun create(params: SandboxJobCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see [create] */ fun create( params: SandboxJobCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** A view of [JobServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun configuration(): ConfigurationServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /sandbox/jobs`, but is otherwise the same as + * [JobServiceAsync.create]. + */ + @MustBeClosed + fun create( + params: SandboxJobCreateParams + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxJobCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/JobServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/JobServiceAsyncImpl.kt index ae344f6c..cbb5ae24 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/JobServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/JobServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.sandbox import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.JobCreateResponse import com.tryfinch.api.models.SandboxJobCreateParams import com.tryfinch.api.services.async.sandbox.jobs.ConfigurationServiceAsync @@ -22,39 +24,64 @@ import java.util.concurrent.CompletableFuture class JobServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : JobServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: JobServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } private val configuration: ConfigurationServiceAsync by lazy { ConfigurationServiceAsyncImpl(clientOptions) } - override fun configuration(): ConfigurationServiceAsync = configuration + override fun withRawResponse(): JobServiceAsync.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun configuration(): ConfigurationServiceAsync = configuration - /** Enqueue a new sandbox job */ override fun create( params: SandboxJobCreateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("sandbox", "jobs") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // post /sandbox/jobs + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + JobServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val configuration: ConfigurationServiceAsync.WithRawResponse by lazy { + ConfigurationServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun configuration(): ConfigurationServiceAsync.WithRawResponse = configuration + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun create( + params: SandboxJobCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("sandbox", "jobs") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/PaymentServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/PaymentServiceAsync.kt index efd8f707..57cf34ff 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/PaymentServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/PaymentServiceAsync.kt @@ -1,24 +1,72 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.sandbox +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.PaymentCreateResponse import com.tryfinch.api.models.SandboxPaymentCreateParams import java.util.concurrent.CompletableFuture interface PaymentServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Add a new sandbox payment */ - @JvmOverloads + fun create(): CompletableFuture = + create(SandboxPaymentCreateParams.none()) + + /** @see [create] */ fun create( params: SandboxPaymentCreateParams = SandboxPaymentCreateParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** Add a new sandbox payment */ + /** @see [create] */ + fun create( + params: SandboxPaymentCreateParams = SandboxPaymentCreateParams.none() + ): CompletableFuture = create(params, RequestOptions.none()) + + /** @see [create] */ fun create(requestOptions: RequestOptions): CompletableFuture = create(SandboxPaymentCreateParams.none(), requestOptions) + + /** + * A view of [PaymentServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /sandbox/payment`, but is otherwise the same as + * [PaymentServiceAsync.create]. + */ + @MustBeClosed + fun create(): CompletableFuture> = + create(SandboxPaymentCreateParams.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxPaymentCreateParams = SandboxPaymentCreateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxPaymentCreateParams = SandboxPaymentCreateParams.none() + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + requestOptions: RequestOptions + ): CompletableFuture> = + create(SandboxPaymentCreateParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/PaymentServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/PaymentServiceAsyncImpl.kt index 13b829d5..6f4667da 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/PaymentServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/PaymentServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.sandbox import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.PaymentCreateResponse import com.tryfinch.api.models.SandboxPaymentCreateParams import java.util.concurrent.CompletableFuture @@ -20,33 +22,53 @@ import java.util.concurrent.CompletableFuture class PaymentServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : PaymentServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: PaymentServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): PaymentServiceAsync.WithRawResponse = withRawResponse - /** Add a new sandbox payment */ override fun create( params: SandboxPaymentCreateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("sandbox", "payment") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // post /sandbox/payment + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PaymentServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: SandboxPaymentCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("sandbox", "payment") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/connections/AccountServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/connections/AccountServiceAsync.kt index ff94d659..600917c9 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/connections/AccountServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/connections/AccountServiceAsync.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.sandbox.connections +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.AccountCreateResponse import com.tryfinch.api.models.AccountUpdateResponse import com.tryfinch.api.models.SandboxConnectionAccountCreateParams @@ -13,8 +13,17 @@ import java.util.concurrent.CompletableFuture interface AccountServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Create a new account for an existing connection (company/provider pair) */ - @JvmOverloads + fun create( + params: SandboxConnectionAccountCreateParams + ): CompletableFuture = create(params, RequestOptions.none()) + + /** @see [create] */ fun create( params: SandboxConnectionAccountCreateParams, requestOptions: RequestOptions = RequestOptions.none(), @@ -24,16 +33,75 @@ interface AccountServiceAsync { * Update an existing sandbox account. Change the connection status to understand how the Finch * API responds. */ - @JvmOverloads + fun update(): CompletableFuture = + update(SandboxConnectionAccountUpdateParams.none()) + + /** @see [update] */ fun update( params: SandboxConnectionAccountUpdateParams = SandboxConnectionAccountUpdateParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture - /** - * Update an existing sandbox account. Change the connection status to understand how the Finch - * API responds. - */ + /** @see [update] */ + fun update( + params: SandboxConnectionAccountUpdateParams = SandboxConnectionAccountUpdateParams.none() + ): CompletableFuture = update(params, RequestOptions.none()) + + /** @see [update] */ fun update(requestOptions: RequestOptions): CompletableFuture = update(SandboxConnectionAccountUpdateParams.none(), requestOptions) + + /** + * A view of [AccountServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /sandbox/connections/accounts`, but is otherwise + * the same as [AccountServiceAsync.create]. + */ + @MustBeClosed + fun create( + params: SandboxConnectionAccountCreateParams + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxConnectionAccountCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `put /sandbox/connections/accounts`, but is otherwise the + * same as [AccountServiceAsync.update]. + */ + @MustBeClosed + fun update(): CompletableFuture> = + update(SandboxConnectionAccountUpdateParams.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: SandboxConnectionAccountUpdateParams = + SandboxConnectionAccountUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see [update] */ + @MustBeClosed + fun update( + params: SandboxConnectionAccountUpdateParams = + SandboxConnectionAccountUpdateParams.none() + ): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + requestOptions: RequestOptions + ): CompletableFuture> = + update(SandboxConnectionAccountUpdateParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/connections/AccountServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/connections/AccountServiceAsyncImpl.kt index b84f6266..5f788805 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/connections/AccountServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/connections/AccountServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.sandbox.connections import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.AccountCreateResponse import com.tryfinch.api.models.AccountUpdateResponse import com.tryfinch.api.models.SandboxConnectionAccountCreateParams @@ -22,64 +24,91 @@ import java.util.concurrent.CompletableFuture class AccountServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : AccountServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: AccountServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): AccountServiceAsync.WithRawResponse = withRawResponse - /** Create a new account for an existing connection (company/provider pair) */ override fun create( params: SandboxConnectionAccountCreateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("sandbox", "connections", "accounts") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - } + ): CompletableFuture = + // post /sandbox/connections/accounts + withRawResponse().create(params, requestOptions).thenApply { it.parse() } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Update an existing sandbox account. Change the connection status to understand how the Finch - * API responds. - */ override fun update( params: SandboxConnectionAccountUpdateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("sandbox", "connections", "accounts") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // put /sandbox/connections/accounts + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AccountServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: SandboxConnectionAccountCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("sandbox", "connections", "accounts") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun update( + params: SandboxConnectionAccountUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .addPathSegments("sandbox", "connections", "accounts") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/jobs/ConfigurationServiceAsync.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/jobs/ConfigurationServiceAsync.kt index 89dd69a8..683e02e8 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/jobs/ConfigurationServiceAsync.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/jobs/ConfigurationServiceAsync.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.async.sandbox.jobs +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.SandboxJobConfiguration import com.tryfinch.api.models.SandboxJobConfigurationRetrieveParams import com.tryfinch.api.models.SandboxJobConfigurationUpdateParams @@ -12,22 +12,94 @@ import java.util.concurrent.CompletableFuture interface ConfigurationServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Get configurations for sandbox jobs */ - @JvmOverloads + fun retrieve(): CompletableFuture> = + retrieve(SandboxJobConfigurationRetrieveParams.none()) + + /** @see [retrieve] */ fun retrieve( params: SandboxJobConfigurationRetrieveParams = SandboxJobConfigurationRetrieveParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture> - /** Get configurations for sandbox jobs */ + /** @see [retrieve] */ + fun retrieve( + params: SandboxJobConfigurationRetrieveParams = SandboxJobConfigurationRetrieveParams.none() + ): CompletableFuture> = retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ fun retrieve(requestOptions: RequestOptions): CompletableFuture> = retrieve(SandboxJobConfigurationRetrieveParams.none(), requestOptions) /** Update configurations for sandbox jobs */ - @JvmOverloads + fun update( + params: SandboxJobConfigurationUpdateParams + ): CompletableFuture = update(params, RequestOptions.none()) + + /** @see [update] */ fun update( params: SandboxJobConfigurationUpdateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** + * A view of [ConfigurationServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /sandbox/jobs/configuration`, but is otherwise the + * same as [ConfigurationServiceAsync.retrieve]. + */ + @MustBeClosed + fun retrieve(): CompletableFuture>> = + retrieve(SandboxJobConfigurationRetrieveParams.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: SandboxJobConfigurationRetrieveParams = + SandboxJobConfigurationRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture>> + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: SandboxJobConfigurationRetrieveParams = + SandboxJobConfigurationRetrieveParams.none() + ): CompletableFuture>> = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + requestOptions: RequestOptions + ): CompletableFuture>> = + retrieve(SandboxJobConfigurationRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /sandbox/jobs/configuration`, but is otherwise the + * same as [ConfigurationServiceAsync.update]. + */ + @MustBeClosed + fun update( + params: SandboxJobConfigurationUpdateParams + ): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: SandboxJobConfigurationUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/jobs/ConfigurationServiceAsyncImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/jobs/ConfigurationServiceAsyncImpl.kt index b3ebe7aa..4002444e 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/jobs/ConfigurationServiceAsyncImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/async/sandbox/jobs/ConfigurationServiceAsyncImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.async.sandbox.jobs import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepareAsync -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.SandboxJobConfiguration import com.tryfinch.api.models.SandboxJobConfigurationRetrieveParams import com.tryfinch.api.models.SandboxJobConfigurationUpdateParams @@ -21,62 +23,90 @@ import java.util.concurrent.CompletableFuture class ConfigurationServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : ConfigurationServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ConfigurationServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val retrieveHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): ConfigurationServiceAsync.WithRawResponse = withRawResponse - /** Get configurations for sandbox jobs */ override fun retrieve( params: SandboxJobConfigurationRetrieveParams, requestOptions: RequestOptions, - ): CompletableFuture> { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("sandbox", "jobs", "configuration") - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { retrieveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } - } - } - } + ): CompletableFuture> = + // get /sandbox/jobs/configuration + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Update configurations for sandbox jobs */ override fun update( params: SandboxJobConfigurationUpdateParams, requestOptions: RequestOptions, - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("sandbox", "jobs", "configuration") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepareAsync(clientOptions, params) - return request - .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } - .thenApply { response -> - response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompletableFuture = + // put /sandbox/jobs/configuration + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ConfigurationServiceAsync.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retrieve( + params: SandboxJobConfigurationRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture>> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("sandbox", "jobs", "configuration") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun update( + params: SandboxJobConfigurationUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .addPathSegments("sandbox", "jobs", "configuration") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccessTokenService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccessTokenService.kt index 5eb189ed..0a0b9cf5 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccessTokenService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccessTokenService.kt @@ -1,19 +1,48 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.AccessTokenCreateParams import com.tryfinch.api.models.CreateAccessTokenResponse interface AccessTokenService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Exchange the authorization code for an access token */ - @JvmOverloads + fun create(params: AccessTokenCreateParams): CreateAccessTokenResponse = + create(params, RequestOptions.none()) + + /** @see [create] */ fun create( params: AccessTokenCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CreateAccessTokenResponse + + /** + * A view of [AccessTokenService] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /auth/token`, but is otherwise the same as + * [AccessTokenService.create]. + */ + @MustBeClosed + fun create(params: AccessTokenCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: AccessTokenCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccessTokenServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccessTokenServiceImpl.kt index d1bab69e..40a41b0d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccessTokenServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccessTokenServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,67 +11,90 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.errors.FinchException import com.tryfinch.api.models.AccessTokenCreateParams import com.tryfinch.api.models.CreateAccessTokenResponse +import kotlin.jvm.optionals.getOrNull class AccessTokenServiceImpl internal constructor(private val clientOptions: ClientOptions) : AccessTokenService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: AccessTokenService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): AccessTokenService.WithRawResponse = withRawResponse - /** Exchange the authorization code for an access token */ override fun create( params: AccessTokenCreateParams, requestOptions: RequestOptions, - ): CreateAccessTokenResponse { - val builder = params.toBuilder() + ): CreateAccessTokenResponse = + // post /auth/token + withRawResponse().create(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AccessTokenService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) - if (!params.clientSecret().isPresent) { - if (clientOptions.clientSecret == null || clientOptions.clientSecret.isEmpty()) { - throw FinchException( - "client_secret must be provided as an argument or with the FINCH_CLIENT_SECRET environment variable" - ) + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: AccessTokenCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val builder = params.toBuilder() + + if (!params.clientSecret().isPresent) { + val clientSecret = clientOptions.clientSecret().getOrNull() + if (clientSecret.isNullOrEmpty()) { + throw FinchException( + "client_secret must be provided as an argument or with the FINCH_CLIENT_SECRET environment variable" + ) + } + builder.clientSecret(clientSecret) } - builder.clientSecret(clientOptions.clientSecret) - } - if (!params.clientId().isPresent) { - if (clientOptions.clientId == null || clientOptions.clientId.isEmpty()) { - throw FinchException( - "client_id must be provided as an argument or with the FINCH_CLIENT_ID environment variable" - ) + if (!params.clientId().isPresent) { + val clientId = clientOptions.clientId().getOrNull() + if (clientId.isNullOrEmpty()) { + throw FinchException( + "client_id must be provided as an argument or with the FINCH_CLIENT_ID environment variable" + ) + } + builder.clientId(clientId) } - builder.clientId(clientOptions.clientId) - } - val modifiedParams = builder.build() + val modifiedParams = builder.build() - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("auth", "token") - .putAllQueryParams(clientOptions.queryParams) - .replaceAllQueryParams(params._queryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params._headers()) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("auth", "token") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(modifiedParams._queryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(modifiedParams._headers()) + .body(json(clientOptions.jsonMapper, modifiedParams._body())) + .build() + .prepare(clientOptions, modifiedParams) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccountService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccountService.kt index fb69f10a..9247468f 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccountService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccountService.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.AccountDisconnectParams import com.tryfinch.api.models.AccountIntrospectParams import com.tryfinch.api.models.DisconnectResponse @@ -12,25 +12,100 @@ import com.tryfinch.api.models.Introspection interface AccountService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Disconnect one or more `access_token`s from your application. */ - @JvmOverloads + fun disconnect(): DisconnectResponse = disconnect(AccountDisconnectParams.none()) + + /** @see [disconnect] */ fun disconnect( params: AccountDisconnectParams = AccountDisconnectParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): DisconnectResponse - /** Disconnect one or more `access_token`s from your application. */ + /** @see [disconnect] */ + fun disconnect( + params: AccountDisconnectParams = AccountDisconnectParams.none() + ): DisconnectResponse = disconnect(params, RequestOptions.none()) + + /** @see [disconnect] */ fun disconnect(requestOptions: RequestOptions): DisconnectResponse = disconnect(AccountDisconnectParams.none(), requestOptions) /** Read account information associated with an `access_token` */ - @JvmOverloads + fun introspect(): Introspection = introspect(AccountIntrospectParams.none()) + + /** @see [introspect] */ fun introspect( params: AccountIntrospectParams = AccountIntrospectParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): Introspection - /** Read account information associated with an `access_token` */ + /** @see [introspect] */ + fun introspect( + params: AccountIntrospectParams = AccountIntrospectParams.none() + ): Introspection = introspect(params, RequestOptions.none()) + + /** @see [introspect] */ fun introspect(requestOptions: RequestOptions): Introspection = introspect(AccountIntrospectParams.none(), requestOptions) + + /** A view of [AccountService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /disconnect`, but is otherwise the same as + * [AccountService.disconnect]. + */ + @MustBeClosed + fun disconnect(): HttpResponseFor = + disconnect(AccountDisconnectParams.none()) + + /** @see [disconnect] */ + @MustBeClosed + fun disconnect( + params: AccountDisconnectParams = AccountDisconnectParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [disconnect] */ + @MustBeClosed + fun disconnect( + params: AccountDisconnectParams = AccountDisconnectParams.none() + ): HttpResponseFor = disconnect(params, RequestOptions.none()) + + /** @see [disconnect] */ + @MustBeClosed + fun disconnect(requestOptions: RequestOptions): HttpResponseFor = + disconnect(AccountDisconnectParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /introspect`, but is otherwise the same as + * [AccountService.introspect]. + */ + @MustBeClosed + fun introspect(): HttpResponseFor = + introspect(AccountIntrospectParams.none()) + + /** @see [introspect] */ + @MustBeClosed + fun introspect( + params: AccountIntrospectParams = AccountIntrospectParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [introspect] */ + @MustBeClosed + fun introspect( + params: AccountIntrospectParams = AccountIntrospectParams.none() + ): HttpResponseFor = introspect(params, RequestOptions.none()) + + /** @see [introspect] */ + @MustBeClosed + fun introspect(requestOptions: RequestOptions): HttpResponseFor = + introspect(AccountIntrospectParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccountServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccountServiceImpl.kt index 45a7f120..84261e55 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccountServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/AccountServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.AccountDisconnectParams import com.tryfinch.api.models.AccountIntrospectParams import com.tryfinch.api.models.DisconnectResponse @@ -21,54 +23,82 @@ import com.tryfinch.api.models.Introspection class AccountServiceImpl internal constructor(private val clientOptions: ClientOptions) : AccountService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: AccountService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val disconnectHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): AccountService.WithRawResponse = withRawResponse - /** Disconnect one or more `access_token`s from your application. */ override fun disconnect( params: AccountDisconnectParams, requestOptions: RequestOptions, - ): DisconnectResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("disconnect") - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { disconnectHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): DisconnectResponse = + // post /disconnect + withRawResponse().disconnect(params, requestOptions).parse() - private val introspectHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Read account information associated with an `access_token` */ override fun introspect( params: AccountIntrospectParams, requestOptions: RequestOptions, - ): Introspection { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("introspect") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { introspectHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): Introspection = + // get /introspect + withRawResponse().introspect(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AccountService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val disconnectHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun disconnect( + params: AccountDisconnectParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("disconnect") + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { disconnectHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val introspectHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun introspect( + params: AccountIntrospectParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("introspect") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { introspectHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ConnectService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ConnectService.kt index daddf9ae..5ac1c0d8 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ConnectService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ConnectService.kt @@ -6,5 +6,16 @@ import com.tryfinch.api.services.blocking.connect.SessionService interface ConnectService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun sessions(): SessionService + + /** A view of [ConnectService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun sessions(): SessionService.WithRawResponse + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ConnectServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ConnectServiceImpl.kt index 52c64ab3..762f16c3 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ConnectServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ConnectServiceImpl.kt @@ -9,7 +9,23 @@ import com.tryfinch.api.services.blocking.connect.SessionServiceImpl class ConnectServiceImpl internal constructor(private val clientOptions: ClientOptions) : ConnectService { + private val withRawResponse: ConnectService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val sessions: SessionService by lazy { SessionServiceImpl(clientOptions) } + override fun withRawResponse(): ConnectService.WithRawResponse = withRawResponse + override fun sessions(): SessionService = sessions + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ConnectService.WithRawResponse { + + private val sessions: SessionService.WithRawResponse by lazy { + SessionServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun sessions(): SessionService.WithRawResponse = sessions + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/HrisService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/HrisService.kt index 5e993449..eae9dfe1 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/HrisService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/HrisService.kt @@ -13,6 +13,11 @@ import com.tryfinch.api.services.blocking.hris.PaymentService interface HrisService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun company(): CompanyService fun directory(): DirectoryService @@ -28,4 +33,24 @@ interface HrisService { fun documents(): DocumentService fun benefits(): BenefitService + + /** A view of [HrisService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun company(): CompanyService.WithRawResponse + + fun directory(): DirectoryService.WithRawResponse + + fun individuals(): IndividualService.WithRawResponse + + fun employments(): EmploymentService.WithRawResponse + + fun payments(): PaymentService.WithRawResponse + + fun payStatements(): PayStatementService.WithRawResponse + + fun documents(): DocumentService.WithRawResponse + + fun benefits(): BenefitService.WithRawResponse + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/HrisServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/HrisServiceImpl.kt index 78b7de0a..15fd8b2e 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/HrisServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/HrisServiceImpl.kt @@ -22,6 +22,10 @@ import com.tryfinch.api.services.blocking.hris.PaymentServiceImpl class HrisServiceImpl internal constructor(private val clientOptions: ClientOptions) : HrisService { + private val withRawResponse: HrisService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val company: CompanyService by lazy { CompanyServiceImpl(clientOptions) } private val directory: DirectoryService by lazy { DirectoryServiceImpl(clientOptions) } @@ -40,6 +44,8 @@ class HrisServiceImpl internal constructor(private val clientOptions: ClientOpti private val benefits: BenefitService by lazy { BenefitServiceImpl(clientOptions) } + override fun withRawResponse(): HrisService.WithRawResponse = withRawResponse + override fun company(): CompanyService = company override fun directory(): DirectoryService = directory @@ -55,4 +61,56 @@ class HrisServiceImpl internal constructor(private val clientOptions: ClientOpti override fun documents(): DocumentService = documents override fun benefits(): BenefitService = benefits + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + HrisService.WithRawResponse { + + private val company: CompanyService.WithRawResponse by lazy { + CompanyServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val directory: DirectoryService.WithRawResponse by lazy { + DirectoryServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val individuals: IndividualService.WithRawResponse by lazy { + IndividualServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val employments: EmploymentService.WithRawResponse by lazy { + EmploymentServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val payments: PaymentService.WithRawResponse by lazy { + PaymentServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val payStatements: PayStatementService.WithRawResponse by lazy { + PayStatementServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val documents: DocumentService.WithRawResponse by lazy { + DocumentServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val benefits: BenefitService.WithRawResponse by lazy { + BenefitServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun company(): CompanyService.WithRawResponse = company + + override fun directory(): DirectoryService.WithRawResponse = directory + + override fun individuals(): IndividualService.WithRawResponse = individuals + + override fun employments(): EmploymentService.WithRawResponse = employments + + override fun payments(): PaymentService.WithRawResponse = payments + + override fun payStatements(): PayStatementService.WithRawResponse = payStatements + + override fun documents(): DocumentService.WithRawResponse = documents + + override fun benefits(): BenefitService.WithRawResponse = benefits + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/JobService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/JobService.kt index 02568840..09461d9d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/JobService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/JobService.kt @@ -7,7 +7,20 @@ import com.tryfinch.api.services.blocking.jobs.ManualService interface JobService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun automated(): AutomatedService fun manual(): ManualService + + /** A view of [JobService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun automated(): AutomatedService.WithRawResponse + + fun manual(): ManualService.WithRawResponse + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/JobServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/JobServiceImpl.kt index 29bdd632..bd836478 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/JobServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/JobServiceImpl.kt @@ -10,11 +10,33 @@ import com.tryfinch.api.services.blocking.jobs.ManualServiceImpl class JobServiceImpl internal constructor(private val clientOptions: ClientOptions) : JobService { + private val withRawResponse: JobService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val automated: AutomatedService by lazy { AutomatedServiceImpl(clientOptions) } private val manual: ManualService by lazy { ManualServiceImpl(clientOptions) } + override fun withRawResponse(): JobService.WithRawResponse = withRawResponse + override fun automated(): AutomatedService = automated override fun manual(): ManualService = manual + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + JobService.WithRawResponse { + + private val automated: AutomatedService.WithRawResponse by lazy { + AutomatedServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val manual: ManualService.WithRawResponse by lazy { + ManualServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun automated(): AutomatedService.WithRawResponse = automated + + override fun manual(): ManualService.WithRawResponse = manual + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/PayrollService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/PayrollService.kt index 4bc0ad62..872b220a 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/PayrollService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/PayrollService.kt @@ -6,5 +6,16 @@ import com.tryfinch.api.services.blocking.payroll.PayGroupService interface PayrollService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun payGroups(): PayGroupService + + /** A view of [PayrollService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun payGroups(): PayGroupService.WithRawResponse + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/PayrollServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/PayrollServiceImpl.kt index ca423f3d..f3e89397 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/PayrollServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/PayrollServiceImpl.kt @@ -9,7 +9,23 @@ import com.tryfinch.api.services.blocking.payroll.PayGroupServiceImpl class PayrollServiceImpl internal constructor(private val clientOptions: ClientOptions) : PayrollService { + private val withRawResponse: PayrollService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val payGroups: PayGroupService by lazy { PayGroupServiceImpl(clientOptions) } + override fun withRawResponse(): PayrollService.WithRawResponse = withRawResponse + override fun payGroups(): PayGroupService = payGroups + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PayrollService.WithRawResponse { + + private val payGroups: PayGroupService.WithRawResponse by lazy { + PayGroupServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun payGroups(): PayGroupService.WithRawResponse = payGroups + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ProviderService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ProviderService.kt index b37847a4..92ef210e 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ProviderService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ProviderService.kt @@ -1,23 +1,63 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.ProviderListPage import com.tryfinch.api.models.ProviderListParams interface ProviderService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Return details on all available payroll and HR systems. */ - @JvmOverloads + fun list(): ProviderListPage = list(ProviderListParams.none()) + + /** @see [list] */ fun list( params: ProviderListParams = ProviderListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): ProviderListPage - /** Return details on all available payroll and HR systems. */ + /** @see [list] */ + fun list(params: ProviderListParams = ProviderListParams.none()): ProviderListPage = + list(params, RequestOptions.none()) + + /** @see [list] */ fun list(requestOptions: RequestOptions): ProviderListPage = list(ProviderListParams.none(), requestOptions) + + /** A view of [ProviderService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /providers`, but is otherwise the same as + * [ProviderService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(ProviderListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: ProviderListParams = ProviderListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [list] */ + @MustBeClosed + fun list( + params: ProviderListParams = ProviderListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(ProviderListParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ProviderServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ProviderServiceImpl.kt index b74c1193..ccfb0392 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ProviderServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/ProviderServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,8 +11,9 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.Provider import com.tryfinch.api.models.ProviderListPage import com.tryfinch.api.models.ProviderListParams @@ -19,36 +21,55 @@ import com.tryfinch.api.models.ProviderListParams class ProviderServiceImpl internal constructor(private val clientOptions: ClientOptions) : ProviderService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ProviderService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val listHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): ProviderService.WithRawResponse = withRawResponse - /** Return details on all available payroll and HR systems. */ override fun list( params: ProviderListParams, requestOptions: RequestOptions, - ): ProviderListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("providers") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } - } - .let { - ProviderListPage.of( - this, - params, - ProviderListPage.Response.builder().items(it).build(), - ) + ): ProviderListPage = + // get /providers + withRawResponse().list(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ProviderService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun list( + params: ProviderListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("providers") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + ProviderListPage.of( + ProviderServiceImpl(clientOptions), + params, + ProviderListPage.Response.builder().items(it).build(), + ) + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/RequestForwardingService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/RequestForwardingService.kt index 7bcd0174..2d29034b 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/RequestForwardingService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/RequestForwardingService.kt @@ -1,23 +1,55 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.RequestForwardingForwardParams import com.tryfinch.api.models.RequestForwardingForwardResponse interface RequestForwardingService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** * The Forward API allows you to make direct requests to an employment system. If Finch’s * unified API doesn’t have a data model that cleanly fits your needs, then Forward allows you * to push or pull data models directly against an integration’s API. */ - @JvmOverloads + fun forward(params: RequestForwardingForwardParams): RequestForwardingForwardResponse = + forward(params, RequestOptions.none()) + + /** @see [forward] */ fun forward( params: RequestForwardingForwardParams, requestOptions: RequestOptions = RequestOptions.none(), ): RequestForwardingForwardResponse + + /** + * A view of [RequestForwardingService] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /forward`, but is otherwise the same as + * [RequestForwardingService.forward]. + */ + @MustBeClosed + fun forward( + params: RequestForwardingForwardParams + ): HttpResponseFor = + forward(params, RequestOptions.none()) + + /** @see [forward] */ + @MustBeClosed + fun forward( + params: RequestForwardingForwardParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/RequestForwardingServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/RequestForwardingServiceImpl.kt index 8121df1d..f68e8ce7 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/RequestForwardingServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/RequestForwardingServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,44 +11,60 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.RequestForwardingForwardParams import com.tryfinch.api.models.RequestForwardingForwardResponse class RequestForwardingServiceImpl internal constructor(private val clientOptions: ClientOptions) : RequestForwardingService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: RequestForwardingService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val forwardHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): RequestForwardingService.WithRawResponse = withRawResponse - /** - * The Forward API allows you to make direct requests to an employment system. If Finch’s - * unified API doesn’t have a data model that cleanly fits your needs, then Forward allows you - * to push or pull data models directly against an integration’s API. - */ override fun forward( params: RequestForwardingForwardParams, requestOptions: RequestOptions, - ): RequestForwardingForwardResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("forward") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { forwardHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): RequestForwardingForwardResponse = + // post /forward + withRawResponse().forward(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + RequestForwardingService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val forwardHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun forward( + params: RequestForwardingForwardParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("forward") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { forwardHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/SandboxService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/SandboxService.kt index ca8510ec..413e04e5 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/SandboxService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/SandboxService.kt @@ -12,6 +12,11 @@ import com.tryfinch.api.services.blocking.sandbox.PaymentService interface SandboxService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun connections(): ConnectionService fun company(): CompanyService @@ -25,4 +30,22 @@ interface SandboxService { fun payment(): PaymentService fun jobs(): JobService + + /** A view of [SandboxService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun connections(): ConnectionService.WithRawResponse + + fun company(): CompanyService.WithRawResponse + + fun directory(): DirectoryService.WithRawResponse + + fun individual(): IndividualService.WithRawResponse + + fun employment(): EmploymentService.WithRawResponse + + fun payment(): PaymentService.WithRawResponse + + fun jobs(): JobService.WithRawResponse + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/SandboxServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/SandboxServiceImpl.kt index 7eeca782..a52a4ba6 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/SandboxServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/SandboxServiceImpl.kt @@ -21,6 +21,10 @@ import com.tryfinch.api.services.blocking.sandbox.PaymentServiceImpl class SandboxServiceImpl internal constructor(private val clientOptions: ClientOptions) : SandboxService { + private val withRawResponse: SandboxService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + private val connections: ConnectionService by lazy { ConnectionServiceImpl(clientOptions) } private val company: CompanyService by lazy { CompanyServiceImpl(clientOptions) } @@ -35,6 +39,8 @@ class SandboxServiceImpl internal constructor(private val clientOptions: ClientO private val jobs: JobService by lazy { JobServiceImpl(clientOptions) } + override fun withRawResponse(): SandboxService.WithRawResponse = withRawResponse + override fun connections(): ConnectionService = connections override fun company(): CompanyService = company @@ -48,4 +54,50 @@ class SandboxServiceImpl internal constructor(private val clientOptions: ClientO override fun payment(): PaymentService = payment override fun jobs(): JobService = jobs + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + SandboxService.WithRawResponse { + + private val connections: ConnectionService.WithRawResponse by lazy { + ConnectionServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val company: CompanyService.WithRawResponse by lazy { + CompanyServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val directory: DirectoryService.WithRawResponse by lazy { + DirectoryServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val individual: IndividualService.WithRawResponse by lazy { + IndividualServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val employment: EmploymentService.WithRawResponse by lazy { + EmploymentServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val payment: PaymentService.WithRawResponse by lazy { + PaymentServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val jobs: JobService.WithRawResponse by lazy { + JobServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun connections(): ConnectionService.WithRawResponse = connections + + override fun company(): CompanyService.WithRawResponse = company + + override fun directory(): DirectoryService.WithRawResponse = directory + + override fun individual(): IndividualService.WithRawResponse = individual + + override fun employment(): EmploymentService.WithRawResponse = employment + + override fun payment(): PaymentService.WithRawResponse = payment + + override fun jobs(): JobService.WithRawResponse = jobs + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/WebhookServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/WebhookServiceImpl.kt index 6cb6f7b2..88069c27 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/WebhookServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/WebhookServiceImpl.kt @@ -5,10 +5,7 @@ package com.tryfinch.api.services.blocking import com.fasterxml.jackson.core.JsonProcessingException import com.tryfinch.api.core.ClientOptions import com.tryfinch.api.core.getRequiredHeader -import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.http.Headers -import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.errors.FinchException import com.tryfinch.api.models.WebhookEvent import java.security.MessageDigest @@ -17,12 +14,11 @@ import java.time.Instant import java.util.Base64 import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec +import kotlin.jvm.optionals.getOrNull class WebhookServiceImpl internal constructor(private val clientOptions: ClientOptions) : WebhookService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) - override fun unwrap(payload: String, headers: Headers, secret: String?): WebhookEvent { verifySignature(payload, headers, secret) return try { @@ -35,7 +31,7 @@ class WebhookServiceImpl internal constructor(private val clientOptions: ClientO override fun verifySignature(payload: String, headers: Headers, secret: String?) { val webhookSecret = secret - ?: clientOptions.webhookSecret + ?: clientOptions.webhookSecret().getOrNull() ?: throw FinchException( "The webhook secret must either be set using the env var, FINCH_WEBHOOK_SECRET, on the client class, or passed to this method" ) diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/connect/SessionService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/connect/SessionService.kt index dc3e860f..ba280313 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/connect/SessionService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/connect/SessionService.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.connect +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.ConnectSessionNewParams import com.tryfinch.api.models.ConnectSessionReauthenticateParams import com.tryfinch.api.models.SessionNewResponse @@ -12,17 +12,64 @@ import com.tryfinch.api.models.SessionReauthenticateResponse interface SessionService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Create a new connect session for an employer */ - @JvmOverloads + fun new_(params: ConnectSessionNewParams): SessionNewResponse = + new_(params, RequestOptions.none()) + + /** @see [new_] */ fun new_( params: ConnectSessionNewParams, requestOptions: RequestOptions = RequestOptions.none(), ): SessionNewResponse /** Create a new Connect session for reauthenticating an existing connection */ - @JvmOverloads + fun reauthenticate(params: ConnectSessionReauthenticateParams): SessionReauthenticateResponse = + reauthenticate(params, RequestOptions.none()) + + /** @see [reauthenticate] */ fun reauthenticate( params: ConnectSessionReauthenticateParams, requestOptions: RequestOptions = RequestOptions.none(), ): SessionReauthenticateResponse + + /** A view of [SessionService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /connect/sessions`, but is otherwise the same as + * [SessionService.new_]. + */ + @MustBeClosed + fun new_(params: ConnectSessionNewParams): HttpResponseFor = + new_(params, RequestOptions.none()) + + /** @see [new_] */ + @MustBeClosed + fun new_( + params: ConnectSessionNewParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `post /connect/sessions/reauthenticate`, but is otherwise + * the same as [SessionService.reauthenticate]. + */ + @MustBeClosed + fun reauthenticate( + params: ConnectSessionReauthenticateParams + ): HttpResponseFor = + reauthenticate(params, RequestOptions.none()) + + /** @see [reauthenticate] */ + @MustBeClosed + fun reauthenticate( + params: ConnectSessionReauthenticateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/connect/SessionServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/connect/SessionServiceImpl.kt index 98ac5eb3..70986f09 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/connect/SessionServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/connect/SessionServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.connect import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.ConnectSessionNewParams import com.tryfinch.api.models.ConnectSessionReauthenticateParams import com.tryfinch.api.models.SessionNewResponse @@ -21,56 +23,84 @@ import com.tryfinch.api.models.SessionReauthenticateResponse class SessionServiceImpl internal constructor(private val clientOptions: ClientOptions) : SessionService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: SessionService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val newHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): SessionService.WithRawResponse = withRawResponse - /** Create a new connect session for an employer */ override fun new_( params: ConnectSessionNewParams, requestOptions: RequestOptions, - ): SessionNewResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("connect", "sessions") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { newHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): SessionNewResponse = + // post /connect/sessions + withRawResponse().new_(params, requestOptions).parse() - private val reauthenticateHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Create a new Connect session for reauthenticating an existing connection */ override fun reauthenticate( params: ConnectSessionReauthenticateParams, requestOptions: RequestOptions, - ): SessionReauthenticateResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("connect", "sessions", "reauthenticate") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { reauthenticateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): SessionReauthenticateResponse = + // post /connect/sessions/reauthenticate + withRawResponse().reauthenticate(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + SessionService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val newHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun new_( + params: ConnectSessionNewParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("connect", "sessions") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { newHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val reauthenticateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun reauthenticate( + params: ConnectSessionReauthenticateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("connect", "sessions", "reauthenticate") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { reauthenticateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/BenefitService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/BenefitService.kt index 6b03b8da..0625d51a 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/BenefitService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/BenefitService.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.CompanyBenefit import com.tryfinch.api.models.CreateCompanyBenefitsResponse import com.tryfinch.api.models.HrisBenefitCreateParams @@ -19,61 +19,209 @@ import com.tryfinch.api.services.blocking.hris.benefits.IndividualService interface BenefitService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun individuals(): IndividualService /** * Creates a new company-wide deduction or contribution. Please use the `/providers` endpoint to * view available types for each provider. */ - @JvmOverloads + fun create(): CreateCompanyBenefitsResponse = create(HrisBenefitCreateParams.none()) + + /** @see [create] */ fun create( params: HrisBenefitCreateParams = HrisBenefitCreateParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): CreateCompanyBenefitsResponse - /** - * Creates a new company-wide deduction or contribution. Please use the `/providers` endpoint to - * view available types for each provider. - */ + /** @see [create] */ + fun create( + params: HrisBenefitCreateParams = HrisBenefitCreateParams.none() + ): CreateCompanyBenefitsResponse = create(params, RequestOptions.none()) + + /** @see [create] */ fun create(requestOptions: RequestOptions): CreateCompanyBenefitsResponse = create(HrisBenefitCreateParams.none(), requestOptions) /** Lists deductions and contributions information for a given item */ - @JvmOverloads + fun retrieve(params: HrisBenefitRetrieveParams): CompanyBenefit = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ fun retrieve( params: HrisBenefitRetrieveParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompanyBenefit /** Updates an existing company-wide deduction or contribution */ - @JvmOverloads + fun update(params: HrisBenefitUpdateParams): UpdateCompanyBenefitResponse = + update(params, RequestOptions.none()) + + /** @see [update] */ fun update( params: HrisBenefitUpdateParams, requestOptions: RequestOptions = RequestOptions.none(), ): UpdateCompanyBenefitResponse /** List all company-wide deductions and contributions. */ - @JvmOverloads + fun list(): HrisBenefitListPage = list(HrisBenefitListParams.none()) + + /** @see [list] */ fun list( params: HrisBenefitListParams = HrisBenefitListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): HrisBenefitListPage - /** List all company-wide deductions and contributions. */ + /** @see [list] */ + fun list(params: HrisBenefitListParams = HrisBenefitListParams.none()): HrisBenefitListPage = + list(params, RequestOptions.none()) + + /** @see [list] */ fun list(requestOptions: RequestOptions): HrisBenefitListPage = list(HrisBenefitListParams.none(), requestOptions) /** Get deductions metadata */ - @JvmOverloads + fun listSupportedBenefits(): HrisBenefitListSupportedBenefitsPage = + listSupportedBenefits(HrisBenefitListSupportedBenefitsParams.none()) + + /** @see [listSupportedBenefits] */ fun listSupportedBenefits( params: HrisBenefitListSupportedBenefitsParams = HrisBenefitListSupportedBenefitsParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): HrisBenefitListSupportedBenefitsPage - /** Get deductions metadata */ + /** @see [listSupportedBenefits] */ + fun listSupportedBenefits( + params: HrisBenefitListSupportedBenefitsParams = + HrisBenefitListSupportedBenefitsParams.none() + ): HrisBenefitListSupportedBenefitsPage = listSupportedBenefits(params, RequestOptions.none()) + + /** @see [listSupportedBenefits] */ fun listSupportedBenefits( requestOptions: RequestOptions ): HrisBenefitListSupportedBenefitsPage = listSupportedBenefits(HrisBenefitListSupportedBenefitsParams.none(), requestOptions) + + /** A view of [BenefitService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun individuals(): IndividualService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /employer/benefits`, but is otherwise the same as + * [BenefitService.create]. + */ + @MustBeClosed + fun create(): HttpResponseFor = + create(HrisBenefitCreateParams.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: HrisBenefitCreateParams = HrisBenefitCreateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [create] */ + @MustBeClosed + fun create( + params: HrisBenefitCreateParams = HrisBenefitCreateParams.none() + ): HttpResponseFor = create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create(requestOptions: RequestOptions): HttpResponseFor = + create(HrisBenefitCreateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /employer/benefits/{benefit_id}`, but is otherwise + * the same as [BenefitService.retrieve]. + */ + @MustBeClosed + fun retrieve(params: HrisBenefitRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: HrisBenefitRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `post /employer/benefits/{benefit_id}`, but is otherwise + * the same as [BenefitService.update]. + */ + @MustBeClosed + fun update(params: HrisBenefitUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: HrisBenefitUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /employer/benefits`, but is otherwise the same as + * [BenefitService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(HrisBenefitListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisBenefitListParams = HrisBenefitListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisBenefitListParams = HrisBenefitListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(HrisBenefitListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /employer/benefits/meta`, but is otherwise the same + * as [BenefitService.listSupportedBenefits]. + */ + @MustBeClosed + fun listSupportedBenefits(): HttpResponseFor = + listSupportedBenefits(HrisBenefitListSupportedBenefitsParams.none()) + + /** @see [listSupportedBenefits] */ + @MustBeClosed + fun listSupportedBenefits( + params: HrisBenefitListSupportedBenefitsParams = + HrisBenefitListSupportedBenefitsParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [listSupportedBenefits] */ + @MustBeClosed + fun listSupportedBenefits( + params: HrisBenefitListSupportedBenefitsParams = + HrisBenefitListSupportedBenefitsParams.none() + ): HttpResponseFor = + listSupportedBenefits(params, RequestOptions.none()) + + /** @see [listSupportedBenefits] */ + @MustBeClosed + fun listSupportedBenefits( + requestOptions: RequestOptions + ): HttpResponseFor = + listSupportedBenefits(HrisBenefitListSupportedBenefitsParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/BenefitServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/BenefitServiceImpl.kt index 212bc6bc..dc678dfd 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/BenefitServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/BenefitServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.CompanyBenefit import com.tryfinch.api.models.CreateCompanyBenefitsResponse import com.tryfinch.api.models.HrisBenefitCreateParams @@ -30,150 +32,212 @@ import com.tryfinch.api.services.blocking.hris.benefits.IndividualServiceImpl class BenefitServiceImpl internal constructor(private val clientOptions: ClientOptions) : BenefitService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: BenefitService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } private val individuals: IndividualService by lazy { IndividualServiceImpl(clientOptions) } - override fun individuals(): IndividualService = individuals + override fun withRawResponse(): BenefitService.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun individuals(): IndividualService = individuals - /** - * Creates a new company-wide deduction or contribution. Please use the `/providers` endpoint to - * view available types for each provider. - */ override fun create( params: HrisBenefitCreateParams, requestOptions: RequestOptions, - ): CreateCompanyBenefitsResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("employer", "benefits") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): CreateCompanyBenefitsResponse = + // post /employer/benefits + withRawResponse().create(params, requestOptions).parse() - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Lists deductions and contributions information for a given item */ override fun retrieve( params: HrisBenefitRetrieveParams, requestOptions: RequestOptions, - ): CompanyBenefit { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "benefits", params.getPathParam(0)) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { retrieveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): CompanyBenefit = + // get /employer/benefits/{benefit_id} + withRawResponse().retrieve(params, requestOptions).parse() - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Updates an existing company-wide deduction or contribution */ override fun update( params: HrisBenefitUpdateParams, requestOptions: RequestOptions, - ): UpdateCompanyBenefitResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("employer", "benefits", params.getPathParam(0)) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } - - private val listHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) + ): UpdateCompanyBenefitResponse = + // post /employer/benefits/{benefit_id} + withRawResponse().update(params, requestOptions).parse() - /** List all company-wide deductions and contributions. */ override fun list( params: HrisBenefitListParams, requestOptions: RequestOptions, - ): HrisBenefitListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "benefits") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } - } - .let { - HrisBenefitListPage.of( - this, - params, - HrisBenefitListPage.Response.builder().items(it).build(), - ) - } - } + ): HrisBenefitListPage = + // get /employer/benefits + withRawResponse().list(params, requestOptions).parse() - private val listSupportedBenefitsHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Get deductions metadata */ override fun listSupportedBenefits( params: HrisBenefitListSupportedBenefitsParams, requestOptions: RequestOptions, - ): HrisBenefitListSupportedBenefitsPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "benefits", "meta") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listSupportedBenefitsHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } + ): HrisBenefitListSupportedBenefitsPage = + // get /employer/benefits/meta + withRawResponse().listSupportedBenefits(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + BenefitService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val individuals: IndividualService.WithRawResponse by lazy { + IndividualServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun individuals(): IndividualService.WithRawResponse = individuals + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: HrisBenefitCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("employer", "benefits") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun retrieve( + params: HrisBenefitRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "benefits", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun update( + params: HrisBenefitUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("employer", "benefits", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun list( + params: HrisBenefitListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "benefits") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + HrisBenefitListPage.of( + BenefitServiceImpl(clientOptions), + params, + HrisBenefitListPage.Response.builder().items(it).build(), + ) + } } - .let { - HrisBenefitListSupportedBenefitsPage.of( - this, - params, - HrisBenefitListSupportedBenefitsPage.Response.builder().items(it).build(), - ) + } + + private val listSupportedBenefitsHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun listSupportedBenefits( + params: HrisBenefitListSupportedBenefitsParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "benefits", "meta") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { listSupportedBenefitsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + HrisBenefitListSupportedBenefitsPage.of( + BenefitServiceImpl(clientOptions), + params, + HrisBenefitListSupportedBenefitsPage.Response.builder() + .items(it) + .build(), + ) + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/CompanyService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/CompanyService.kt index def4fcd0..82ff7c15 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/CompanyService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/CompanyService.kt @@ -1,23 +1,68 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.Company import com.tryfinch.api.models.HrisCompanyRetrieveParams +import com.tryfinch.api.services.blocking.hris.company.PayStatementItemService interface CompanyService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + fun payStatementItem(): PayStatementItemService + /** Read basic company data */ - @JvmOverloads + fun retrieve(): Company = retrieve(HrisCompanyRetrieveParams.none()) + + /** @see [retrieve] */ fun retrieve( params: HrisCompanyRetrieveParams = HrisCompanyRetrieveParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): Company - /** Read basic company data */ + /** @see [retrieve] */ + fun retrieve(params: HrisCompanyRetrieveParams = HrisCompanyRetrieveParams.none()): Company = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ fun retrieve(requestOptions: RequestOptions): Company = retrieve(HrisCompanyRetrieveParams.none(), requestOptions) + + /** A view of [CompanyService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun payStatementItem(): PayStatementItemService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /employer/company`, but is otherwise the same as + * [CompanyService.retrieve]. + */ + @MustBeClosed + fun retrieve(): HttpResponseFor = retrieve(HrisCompanyRetrieveParams.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: HrisCompanyRetrieveParams = HrisCompanyRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: HrisCompanyRetrieveParams = HrisCompanyRetrieveParams.none() + ): HttpResponseFor = retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve(requestOptions: RequestOptions): HttpResponseFor = + retrieve(HrisCompanyRetrieveParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/CompanyServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/CompanyServiceImpl.kt index f8642c39..89a1abcf 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/CompanyServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/CompanyServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,37 +11,71 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.Company import com.tryfinch.api.models.HrisCompanyRetrieveParams +import com.tryfinch.api.services.blocking.hris.company.PayStatementItemService +import com.tryfinch.api.services.blocking.hris.company.PayStatementItemServiceImpl class CompanyServiceImpl internal constructor(private val clientOptions: ClientOptions) : CompanyService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: CompanyService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val payStatementItem: PayStatementItemService by lazy { + PayStatementItemServiceImpl(clientOptions) + } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): CompanyService.WithRawResponse = withRawResponse + + override fun payStatementItem(): PayStatementItemService = payStatementItem - /** Read basic company data */ override fun retrieve( params: HrisCompanyRetrieveParams, requestOptions: RequestOptions, - ): Company { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "company") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { retrieveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): Company = + // get /employer/company + withRawResponse().retrieve(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + CompanyService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val payStatementItem: PayStatementItemService.WithRawResponse by lazy { + PayStatementItemServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun payStatementItem(): PayStatementItemService.WithRawResponse = payStatementItem + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun retrieve( + params: HrisCompanyRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "company") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DirectoryService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DirectoryService.kt index 6304c989..dc9adbd0 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DirectoryService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DirectoryService.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.HrisDirectoryListIndividualsPage import com.tryfinch.api.models.HrisDirectoryListIndividualsParams import com.tryfinch.api.models.HrisDirectoryListPage @@ -12,27 +12,111 @@ import com.tryfinch.api.models.HrisDirectoryListParams interface DirectoryService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Read company directory and organization structure */ - @JvmOverloads + fun list(): HrisDirectoryListPage = list(HrisDirectoryListParams.none()) + + /** @see [list] */ fun list( params: HrisDirectoryListParams = HrisDirectoryListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): HrisDirectoryListPage - /** Read company directory and organization structure */ + /** @see [list] */ + fun list( + params: HrisDirectoryListParams = HrisDirectoryListParams.none() + ): HrisDirectoryListPage = list(params, RequestOptions.none()) + + /** @see [list] */ fun list(requestOptions: RequestOptions): HrisDirectoryListPage = list(HrisDirectoryListParams.none(), requestOptions) /** Read company directory and organization structure */ @Deprecated("use `list` instead") - @JvmOverloads + fun listIndividuals(): HrisDirectoryListIndividualsPage = + listIndividuals(HrisDirectoryListIndividualsParams.none()) + + /** @see [listIndividuals] */ + @Deprecated("use `list` instead") fun listIndividuals( params: HrisDirectoryListIndividualsParams = HrisDirectoryListIndividualsParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): HrisDirectoryListIndividualsPage - /** Read company directory and organization structure */ + /** @see [listIndividuals] */ + @Deprecated("use `list` instead") + fun listIndividuals( + params: HrisDirectoryListIndividualsParams = HrisDirectoryListIndividualsParams.none() + ): HrisDirectoryListIndividualsPage = listIndividuals(params, RequestOptions.none()) + + /** @see [listIndividuals] */ @Deprecated("use `list` instead") fun listIndividuals(requestOptions: RequestOptions): HrisDirectoryListIndividualsPage = listIndividuals(HrisDirectoryListIndividualsParams.none(), requestOptions) + + /** A view of [DirectoryService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /employer/directory`, but is otherwise the same as + * [DirectoryService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(HrisDirectoryListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisDirectoryListParams = HrisDirectoryListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisDirectoryListParams = HrisDirectoryListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(HrisDirectoryListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /employer/directory`, but is otherwise the same as + * [DirectoryService.listIndividuals]. + */ + @Deprecated("use `list` instead") + @MustBeClosed + fun listIndividuals(): HttpResponseFor = + listIndividuals(HrisDirectoryListIndividualsParams.none()) + + /** @see [listIndividuals] */ + @Deprecated("use `list` instead") + @MustBeClosed + fun listIndividuals( + params: HrisDirectoryListIndividualsParams = HrisDirectoryListIndividualsParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [listIndividuals] */ + @Deprecated("use `list` instead") + @MustBeClosed + fun listIndividuals( + params: HrisDirectoryListIndividualsParams = HrisDirectoryListIndividualsParams.none() + ): HttpResponseFor = + listIndividuals(params, RequestOptions.none()) + + /** @see [listIndividuals] */ + @Deprecated("use `list` instead") + @MustBeClosed + fun listIndividuals( + requestOptions: RequestOptions + ): HttpResponseFor = + listIndividuals(HrisDirectoryListIndividualsParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DirectoryServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DirectoryServiceImpl.kt index d20b1bcf..f286831f 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DirectoryServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DirectoryServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,8 +11,9 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.HrisDirectoryListIndividualsPage import com.tryfinch.api.models.HrisDirectoryListIndividualsParams import com.tryfinch.api.models.HrisDirectoryListPage @@ -20,58 +22,95 @@ import com.tryfinch.api.models.HrisDirectoryListParams class DirectoryServiceImpl internal constructor(private val clientOptions: ClientOptions) : DirectoryService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: DirectoryService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): DirectoryService.WithRawResponse = withRawResponse - /** Read company directory and organization structure */ override fun list( params: HrisDirectoryListParams, requestOptions: RequestOptions, - ): HrisDirectoryListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "directory") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - .let { HrisDirectoryListPage.of(this, params, it) } - } + ): HrisDirectoryListPage = + // get /employer/directory + withRawResponse().list(params, requestOptions).parse() - private val listIndividualsHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Read company directory and organization structure */ @Deprecated("use `list` instead") override fun listIndividuals( params: HrisDirectoryListIndividualsParams, requestOptions: RequestOptions, - ): HrisDirectoryListIndividualsPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "directory") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listIndividualsHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): HrisDirectoryListIndividualsPage = + // get /employer/directory + withRawResponse().listIndividuals(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + DirectoryService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun list( + params: HrisDirectoryListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "directory") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisDirectoryListPage.of(DirectoryServiceImpl(clientOptions), params, it) + } + } + } + + private val listIndividualsHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + @Deprecated("use `list` instead") + override fun listIndividuals( + params: HrisDirectoryListIndividualsParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "directory") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { listIndividualsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisDirectoryListIndividualsPage.of( + DirectoryServiceImpl(clientOptions), + params, + it, + ) + } } - .let { HrisDirectoryListIndividualsPage.of(this, params, it) } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DocumentService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DocumentService.kt index ca9377fc..2688fe07 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DocumentService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DocumentService.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.DocumentListResponse import com.tryfinch.api.models.DocumentRetreiveResponse import com.tryfinch.api.models.HrisDocumentListParams @@ -12,18 +12,27 @@ import com.tryfinch.api.models.HrisDocumentRetreiveParams interface DocumentService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** * **Beta:** This endpoint is in beta and may change. Retrieve a list of company-wide documents. */ - @JvmOverloads + fun list(): DocumentListResponse = list(HrisDocumentListParams.none()) + + /** @see [list] */ fun list( params: HrisDocumentListParams = HrisDocumentListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): DocumentListResponse - /** - * **Beta:** This endpoint is in beta and may change. Retrieve a list of company-wide documents. - */ + /** @see [list] */ + fun list(params: HrisDocumentListParams = HrisDocumentListParams.none()): DocumentListResponse = + list(params, RequestOptions.none()) + + /** @see [list] */ fun list(requestOptions: RequestOptions): DocumentListResponse = list(HrisDocumentListParams.none(), requestOptions) @@ -31,9 +40,57 @@ interface DocumentService { * **Beta:** This endpoint is in beta and may change. Retrieve details of a specific document by * its ID. */ - @JvmOverloads + fun retreive(params: HrisDocumentRetreiveParams): DocumentRetreiveResponse = + retreive(params, RequestOptions.none()) + + /** @see [retreive] */ fun retreive( params: HrisDocumentRetreiveParams, requestOptions: RequestOptions = RequestOptions.none(), ): DocumentRetreiveResponse + + /** A view of [DocumentService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /employer/documents`, but is otherwise the same as + * [DocumentService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(HrisDocumentListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisDocumentListParams = HrisDocumentListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisDocumentListParams = HrisDocumentListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(HrisDocumentListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /employer/documents/{document_id}`, but is otherwise + * the same as [DocumentService.retreive]. + */ + @MustBeClosed + fun retreive( + params: HrisDocumentRetreiveParams + ): HttpResponseFor = retreive(params, RequestOptions.none()) + + /** @see [retreive] */ + @MustBeClosed + fun retreive( + params: HrisDocumentRetreiveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DocumentServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DocumentServiceImpl.kt index fb50f412..8ddf997d 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DocumentServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/DocumentServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,8 +11,9 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.DocumentListResponse import com.tryfinch.api.models.DocumentRetreiveResponse import com.tryfinch.api.models.HrisDocumentListParams @@ -20,59 +22,83 @@ import com.tryfinch.api.models.HrisDocumentRetreiveParams class DocumentServiceImpl internal constructor(private val clientOptions: ClientOptions) : DocumentService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: DocumentService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): DocumentService.WithRawResponse = withRawResponse - /** - * **Beta:** This endpoint is in beta and may change. Retrieve a list of company-wide documents. - */ override fun list( params: HrisDocumentListParams, requestOptions: RequestOptions, - ): DocumentListResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "documents") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): DocumentListResponse = + // get /employer/documents + withRawResponse().list(params, requestOptions).parse() - private val retreiveHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * **Beta:** This endpoint is in beta and may change. Retrieve details of a specific document by - * its ID. - */ override fun retreive( params: HrisDocumentRetreiveParams, requestOptions: RequestOptions, - ): DocumentRetreiveResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "documents", params.getPathParam(0)) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { retreiveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): DocumentRetreiveResponse = + // get /employer/documents/{document_id} + withRawResponse().retreive(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + DocumentService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun list( + params: HrisDocumentListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "documents") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retreiveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retreive( + params: HrisDocumentRetreiveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "documents", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { retreiveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/EmploymentService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/EmploymentService.kt index 98beeb34..e2d11244 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/EmploymentService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/EmploymentService.kt @@ -1,19 +1,48 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.HrisEmploymentRetrieveManyPage import com.tryfinch.api.models.HrisEmploymentRetrieveManyParams interface EmploymentService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Read individual employment and income data */ - @JvmOverloads + fun retrieveMany(params: HrisEmploymentRetrieveManyParams): HrisEmploymentRetrieveManyPage = + retrieveMany(params, RequestOptions.none()) + + /** @see [retrieveMany] */ fun retrieveMany( params: HrisEmploymentRetrieveManyParams, requestOptions: RequestOptions = RequestOptions.none(), ): HrisEmploymentRetrieveManyPage + + /** A view of [EmploymentService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /employer/employment`, but is otherwise the same as + * [EmploymentService.retrieveMany]. + */ + @MustBeClosed + fun retrieveMany( + params: HrisEmploymentRetrieveManyParams + ): HttpResponseFor = + retrieveMany(params, RequestOptions.none()) + + /** @see [retrieveMany] */ + @MustBeClosed + fun retrieveMany( + params: HrisEmploymentRetrieveManyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/EmploymentServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/EmploymentServiceImpl.kt index 1f65f3bc..6f5c4811 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/EmploymentServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/EmploymentServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,41 +11,67 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.HrisEmploymentRetrieveManyPage import com.tryfinch.api.models.HrisEmploymentRetrieveManyParams class EmploymentServiceImpl internal constructor(private val clientOptions: ClientOptions) : EmploymentService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: EmploymentService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val retrieveManyHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): EmploymentService.WithRawResponse = withRawResponse - /** Read individual employment and income data */ override fun retrieveMany( params: HrisEmploymentRetrieveManyParams, requestOptions: RequestOptions, - ): HrisEmploymentRetrieveManyPage { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("employer", "employment") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { retrieveManyHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): HrisEmploymentRetrieveManyPage = + // post /employer/employment + withRawResponse().retrieveMany(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + EmploymentService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveManyHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retrieveMany( + params: HrisEmploymentRetrieveManyParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("employer", "employment") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { retrieveManyHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisEmploymentRetrieveManyPage.of( + EmploymentServiceImpl(clientOptions), + params, + it, + ) + } } - .let { HrisEmploymentRetrieveManyPage.of(this, params, it) } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/IndividualService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/IndividualService.kt index 1c0a766b..fa435bf7 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/IndividualService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/IndividualService.kt @@ -1,23 +1,69 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.HrisIndividualRetrieveManyPage import com.tryfinch.api.models.HrisIndividualRetrieveManyParams interface IndividualService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Read individual data, excluding income and employment data */ - @JvmOverloads + fun retrieveMany(): HrisIndividualRetrieveManyPage = + retrieveMany(HrisIndividualRetrieveManyParams.none()) + + /** @see [retrieveMany] */ fun retrieveMany( params: HrisIndividualRetrieveManyParams = HrisIndividualRetrieveManyParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): HrisIndividualRetrieveManyPage - /** Read individual data, excluding income and employment data */ + /** @see [retrieveMany] */ + fun retrieveMany( + params: HrisIndividualRetrieveManyParams = HrisIndividualRetrieveManyParams.none() + ): HrisIndividualRetrieveManyPage = retrieveMany(params, RequestOptions.none()) + + /** @see [retrieveMany] */ fun retrieveMany(requestOptions: RequestOptions): HrisIndividualRetrieveManyPage = retrieveMany(HrisIndividualRetrieveManyParams.none(), requestOptions) + + /** A view of [IndividualService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /employer/individual`, but is otherwise the same as + * [IndividualService.retrieveMany]. + */ + @MustBeClosed + fun retrieveMany(): HttpResponseFor = + retrieveMany(HrisIndividualRetrieveManyParams.none()) + + /** @see [retrieveMany] */ + @MustBeClosed + fun retrieveMany( + params: HrisIndividualRetrieveManyParams = HrisIndividualRetrieveManyParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [retrieveMany] */ + @MustBeClosed + fun retrieveMany( + params: HrisIndividualRetrieveManyParams = HrisIndividualRetrieveManyParams.none() + ): HttpResponseFor = + retrieveMany(params, RequestOptions.none()) + + /** @see [retrieveMany] */ + @MustBeClosed + fun retrieveMany( + requestOptions: RequestOptions + ): HttpResponseFor = + retrieveMany(HrisIndividualRetrieveManyParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/IndividualServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/IndividualServiceImpl.kt index 55949402..1eb3e10c 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/IndividualServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/IndividualServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,41 +11,67 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.HrisIndividualRetrieveManyPage import com.tryfinch.api.models.HrisIndividualRetrieveManyParams class IndividualServiceImpl internal constructor(private val clientOptions: ClientOptions) : IndividualService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: IndividualService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val retrieveManyHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): IndividualService.WithRawResponse = withRawResponse - /** Read individual data, excluding income and employment data */ override fun retrieveMany( params: HrisIndividualRetrieveManyParams, requestOptions: RequestOptions, - ): HrisIndividualRetrieveManyPage { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("employer", "individual") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { retrieveManyHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): HrisIndividualRetrieveManyPage = + // post /employer/individual + withRawResponse().retrieveMany(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + IndividualService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveManyHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retrieveMany( + params: HrisIndividualRetrieveManyParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("employer", "individual") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { retrieveManyHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisIndividualRetrieveManyPage.of( + IndividualServiceImpl(clientOptions), + params, + it, + ) + } } - .let { HrisIndividualRetrieveManyPage.of(this, params, it) } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PayStatementService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PayStatementService.kt index aa04af04..de869d8c 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PayStatementService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PayStatementService.kt @@ -1,23 +1,54 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.HrisPayStatementRetrieveManyPage import com.tryfinch.api.models.HrisPayStatementRetrieveManyParams interface PayStatementService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** * Read detailed pay statements for each individual. * * Deduction and contribution types are supported by the payroll systems that supports Benefits. */ - @JvmOverloads + fun retrieveMany(params: HrisPayStatementRetrieveManyParams): HrisPayStatementRetrieveManyPage = + retrieveMany(params, RequestOptions.none()) + + /** @see [retrieveMany] */ fun retrieveMany( params: HrisPayStatementRetrieveManyParams, requestOptions: RequestOptions = RequestOptions.none(), ): HrisPayStatementRetrieveManyPage + + /** + * A view of [PayStatementService] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /employer/pay-statement`, but is otherwise the same + * as [PayStatementService.retrieveMany]. + */ + @MustBeClosed + fun retrieveMany( + params: HrisPayStatementRetrieveManyParams + ): HttpResponseFor = + retrieveMany(params, RequestOptions.none()) + + /** @see [retrieveMany] */ + @MustBeClosed + fun retrieveMany( + params: HrisPayStatementRetrieveManyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PayStatementServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PayStatementServiceImpl.kt index 129ec2f5..2f34f4c3 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PayStatementServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PayStatementServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,45 +11,67 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.HrisPayStatementRetrieveManyPage import com.tryfinch.api.models.HrisPayStatementRetrieveManyParams class PayStatementServiceImpl internal constructor(private val clientOptions: ClientOptions) : PayStatementService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: PayStatementService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val retrieveManyHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): PayStatementService.WithRawResponse = withRawResponse - /** - * Read detailed pay statements for each individual. - * - * Deduction and contribution types are supported by the payroll systems that supports Benefits. - */ override fun retrieveMany( params: HrisPayStatementRetrieveManyParams, requestOptions: RequestOptions, - ): HrisPayStatementRetrieveManyPage { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("employer", "pay-statement") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { retrieveManyHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): HrisPayStatementRetrieveManyPage = + // post /employer/pay-statement + withRawResponse().retrieveMany(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PayStatementService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveManyHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retrieveMany( + params: HrisPayStatementRetrieveManyParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("employer", "pay-statement") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { retrieveManyHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisPayStatementRetrieveManyPage.of( + PayStatementServiceImpl(clientOptions), + params, + it, + ) + } } - .let { HrisPayStatementRetrieveManyPage.of(this, params, it) } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PaymentService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PaymentService.kt index c1f5ea2d..f62d1061 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PaymentService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PaymentService.kt @@ -1,19 +1,46 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.hris +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.HrisPaymentListPage import com.tryfinch.api.models.HrisPaymentListParams interface PaymentService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Read payroll and contractor related payments by the company. */ - @JvmOverloads + fun list(params: HrisPaymentListParams): HrisPaymentListPage = + list(params, RequestOptions.none()) + + /** @see [list] */ fun list( params: HrisPaymentListParams, requestOptions: RequestOptions = RequestOptions.none(), ): HrisPaymentListPage + + /** A view of [PaymentService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /employer/payment`, but is otherwise the same as + * [PaymentService.list]. + */ + @MustBeClosed + fun list(params: HrisPaymentListParams): HttpResponseFor = + list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisPaymentListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PaymentServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PaymentServiceImpl.kt index 3fc047c3..2718c030 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PaymentServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/PaymentServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.hris import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,8 +11,9 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.HrisPaymentListPage import com.tryfinch.api.models.HrisPaymentListParams import com.tryfinch.api.models.Payment @@ -19,36 +21,55 @@ import com.tryfinch.api.models.Payment class PaymentServiceImpl internal constructor(private val clientOptions: ClientOptions) : PaymentService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: PaymentService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val listHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): PaymentService.WithRawResponse = withRawResponse - /** Read payroll and contractor related payments by the company. */ override fun list( params: HrisPaymentListParams, requestOptions: RequestOptions, - ): HrisPaymentListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "payment") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } - } - .let { - HrisPaymentListPage.of( - this, - params, - HrisPaymentListPage.Response.builder().items(it).build(), - ) + ): HrisPaymentListPage = + // get /employer/payment + withRawResponse().list(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PaymentService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun list( + params: HrisPaymentListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "payment") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + HrisPaymentListPage.of( + PaymentServiceImpl(clientOptions), + params, + HrisPaymentListPage.Response.builder().items(it).build(), + ) + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/benefits/IndividualService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/benefits/IndividualService.kt index 4ca4e5f0..f0f36e43 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/benefits/IndividualService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/benefits/IndividualService.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.hris.benefits +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.HrisBenefitIndividualEnrolledIdsParams import com.tryfinch.api.models.HrisBenefitIndividualRetrieveManyBenefitsPage import com.tryfinch.api.models.HrisBenefitIndividualRetrieveManyBenefitsParams @@ -14,24 +14,96 @@ import com.tryfinch.api.models.IndividualEnrolledIdsResponse interface IndividualService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Lists individuals currently enrolled in a given deduction. */ - @JvmOverloads + fun enrolledIds(params: HrisBenefitIndividualEnrolledIdsParams): IndividualEnrolledIdsResponse = + enrolledIds(params, RequestOptions.none()) + + /** @see [enrolledIds] */ fun enrolledIds( params: HrisBenefitIndividualEnrolledIdsParams, requestOptions: RequestOptions = RequestOptions.none(), ): IndividualEnrolledIdsResponse /** Get enrollment information for the given individuals. */ - @JvmOverloads + fun retrieveManyBenefits( + params: HrisBenefitIndividualRetrieveManyBenefitsParams + ): HrisBenefitIndividualRetrieveManyBenefitsPage = + retrieveManyBenefits(params, RequestOptions.none()) + + /** @see [retrieveManyBenefits] */ fun retrieveManyBenefits( params: HrisBenefitIndividualRetrieveManyBenefitsParams, requestOptions: RequestOptions = RequestOptions.none(), ): HrisBenefitIndividualRetrieveManyBenefitsPage /** Unenroll individuals from a deduction or contribution */ - @JvmOverloads + fun unenrollMany( + params: HrisBenefitIndividualUnenrollManyParams + ): HrisBenefitIndividualUnenrollManyPage = unenrollMany(params, RequestOptions.none()) + + /** @see [unenrollMany] */ fun unenrollMany( params: HrisBenefitIndividualUnenrollManyParams, requestOptions: RequestOptions = RequestOptions.none(), ): HrisBenefitIndividualUnenrollManyPage + + /** A view of [IndividualService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /employer/benefits/{benefit_id}/enrolled`, but is + * otherwise the same as [IndividualService.enrolledIds]. + */ + @MustBeClosed + fun enrolledIds( + params: HrisBenefitIndividualEnrolledIdsParams + ): HttpResponseFor = + enrolledIds(params, RequestOptions.none()) + + /** @see [enrolledIds] */ + @MustBeClosed + fun enrolledIds( + params: HrisBenefitIndividualEnrolledIdsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /employer/benefits/{benefit_id}/individuals`, but is + * otherwise the same as [IndividualService.retrieveManyBenefits]. + */ + @MustBeClosed + fun retrieveManyBenefits( + params: HrisBenefitIndividualRetrieveManyBenefitsParams + ): HttpResponseFor = + retrieveManyBenefits(params, RequestOptions.none()) + + /** @see [retrieveManyBenefits] */ + @MustBeClosed + fun retrieveManyBenefits( + params: HrisBenefitIndividualRetrieveManyBenefitsParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `delete /employer/benefits/{benefit_id}/individuals`, but + * is otherwise the same as [IndividualService.unenrollMany]. + */ + @MustBeClosed + fun unenrollMany( + params: HrisBenefitIndividualUnenrollManyParams + ): HttpResponseFor = + unenrollMany(params, RequestOptions.none()) + + /** @see [unenrollMany] */ + @MustBeClosed + fun unenrollMany( + params: HrisBenefitIndividualUnenrollManyParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/benefits/IndividualServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/benefits/IndividualServiceImpl.kt index 51cb9c63..34bf610b 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/benefits/IndividualServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/benefits/IndividualServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.hris.benefits import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.HrisBenefitIndividualEnrolledIdsParams import com.tryfinch.api.models.HrisBenefitIndividualRetrieveManyBenefitsPage import com.tryfinch.api.models.HrisBenefitIndividualRetrieveManyBenefitsParams @@ -25,97 +27,136 @@ import com.tryfinch.api.models.UnenrolledIndividual class IndividualServiceImpl internal constructor(private val clientOptions: ClientOptions) : IndividualService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: IndividualService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val enrolledIdsHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): IndividualService.WithRawResponse = withRawResponse - /** Lists individuals currently enrolled in a given deduction. */ override fun enrolledIds( params: HrisBenefitIndividualEnrolledIdsParams, requestOptions: RequestOptions, - ): IndividualEnrolledIdsResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "benefits", params.getPathParam(0), "enrolled") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { enrolledIdsHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): IndividualEnrolledIdsResponse = + // get /employer/benefits/{benefit_id}/enrolled + withRawResponse().enrolledIds(params, requestOptions).parse() - private val retrieveManyBenefitsHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Get enrollment information for the given individuals. */ override fun retrieveManyBenefits( params: HrisBenefitIndividualRetrieveManyBenefitsParams, requestOptions: RequestOptions, - ): HrisBenefitIndividualRetrieveManyBenefitsPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "benefits", params.getPathParam(0), "individuals") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { retrieveManyBenefitsHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } - } - .let { - HrisBenefitIndividualRetrieveManyBenefitsPage.of( - this, - params, - HrisBenefitIndividualRetrieveManyBenefitsPage.Response.builder() - .items(it) - .build(), - ) - } - } + ): HrisBenefitIndividualRetrieveManyBenefitsPage = + // get /employer/benefits/{benefit_id}/individuals + withRawResponse().retrieveManyBenefits(params, requestOptions).parse() - private val unenrollManyHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Unenroll individuals from a deduction or contribution */ override fun unenrollMany( params: HrisBenefitIndividualUnenrollManyParams, requestOptions: RequestOptions, - ): HrisBenefitIndividualUnenrollManyPage { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("employer", "benefits", params.getPathParam(0), "individuals") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { unenrollManyHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } + ): HrisBenefitIndividualUnenrollManyPage = + // delete /employer/benefits/{benefit_id}/individuals + withRawResponse().unenrollMany(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + IndividualService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val enrolledIdsHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun enrolledIds( + params: HrisBenefitIndividualEnrolledIdsParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "benefits", params._pathParam(0), "enrolled") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { enrolledIdsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveManyBenefitsHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retrieveManyBenefits( + params: HrisBenefitIndividualRetrieveManyBenefitsParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "benefits", params._pathParam(0), "individuals") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { retrieveManyBenefitsHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + HrisBenefitIndividualRetrieveManyBenefitsPage.of( + IndividualServiceImpl(clientOptions), + params, + HrisBenefitIndividualRetrieveManyBenefitsPage.Response.builder() + .items(it) + .build(), + ) + } } - .let { - HrisBenefitIndividualUnenrollManyPage.of( - this, - params, - HrisBenefitIndividualUnenrollManyPage.Response.builder().items(it).build(), - ) + } + + private val unenrollManyHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun unenrollMany( + params: HrisBenefitIndividualUnenrollManyParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .addPathSegments("employer", "benefits", params._pathParam(0), "individuals") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { unenrollManyHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + HrisBenefitIndividualUnenrollManyPage.of( + IndividualServiceImpl(clientOptions), + params, + HrisBenefitIndividualUnenrollManyPage.Response.builder() + .items(it) + .build(), + ) + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/company/PayStatementItemService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/company/PayStatementItemService.kt new file mode 100644 index 00000000..c498a733 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/company/PayStatementItemService.kt @@ -0,0 +1,84 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.services.blocking.hris.company + +import com.google.errorprone.annotations.MustBeClosed +import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.models.HrisCompanyPayStatementItemListPage +import com.tryfinch.api.models.HrisCompanyPayStatementItemListParams +import com.tryfinch.api.services.blocking.hris.company.payStatementItem.RuleService + +interface PayStatementItemService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + fun rules(): RuleService + + /** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Retrieve a list of detailed pay statement items for the access + * token's connection account. + */ + fun list(): HrisCompanyPayStatementItemListPage = + list(HrisCompanyPayStatementItemListParams.none()) + + /** @see [list] */ + fun list( + params: HrisCompanyPayStatementItemListParams = + HrisCompanyPayStatementItemListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HrisCompanyPayStatementItemListPage + + /** @see [list] */ + fun list( + params: HrisCompanyPayStatementItemListParams = HrisCompanyPayStatementItemListParams.none() + ): HrisCompanyPayStatementItemListPage = list(params, RequestOptions.none()) + + /** @see [list] */ + fun list(requestOptions: RequestOptions): HrisCompanyPayStatementItemListPage = + list(HrisCompanyPayStatementItemListParams.none(), requestOptions) + + /** + * A view of [PayStatementItemService] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + fun rules(): RuleService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /employer/pay-statement-item`, but is otherwise the + * same as [PayStatementItemService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = + list(HrisCompanyPayStatementItemListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisCompanyPayStatementItemListParams = + HrisCompanyPayStatementItemListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisCompanyPayStatementItemListParams = + HrisCompanyPayStatementItemListParams.none() + ): HttpResponseFor = + list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + requestOptions: RequestOptions + ): HttpResponseFor = + list(HrisCompanyPayStatementItemListParams.none(), requestOptions) + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/company/PayStatementItemServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/company/PayStatementItemServiceImpl.kt new file mode 100644 index 00000000..3deb88a5 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/company/PayStatementItemServiceImpl.kt @@ -0,0 +1,87 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.services.blocking.hris.company + +import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.handlers.errorHandler +import com.tryfinch.api.core.handlers.jsonHandler +import com.tryfinch.api.core.handlers.withErrorHandler +import com.tryfinch.api.core.http.HttpMethod +import com.tryfinch.api.core.http.HttpRequest +import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable +import com.tryfinch.api.core.prepare +import com.tryfinch.api.models.HrisCompanyPayStatementItemListPage +import com.tryfinch.api.models.HrisCompanyPayStatementItemListParams +import com.tryfinch.api.services.blocking.hris.company.payStatementItem.RuleService +import com.tryfinch.api.services.blocking.hris.company.payStatementItem.RuleServiceImpl + +class PayStatementItemServiceImpl internal constructor(private val clientOptions: ClientOptions) : + PayStatementItemService { + + private val withRawResponse: PayStatementItemService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val rules: RuleService by lazy { RuleServiceImpl(clientOptions) } + + override fun withRawResponse(): PayStatementItemService.WithRawResponse = withRawResponse + + override fun rules(): RuleService = rules + + override fun list( + params: HrisCompanyPayStatementItemListParams, + requestOptions: RequestOptions, + ): HrisCompanyPayStatementItemListPage = + // get /employer/pay-statement-item + withRawResponse().list(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PayStatementItemService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val rules: RuleService.WithRawResponse by lazy { + RuleServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun rules(): RuleService.WithRawResponse = rules + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun list( + params: HrisCompanyPayStatementItemListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "pay-statement-item") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisCompanyPayStatementItemListPage.of( + PayStatementItemServiceImpl(clientOptions), + params, + it, + ) + } + } + } + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/company/payStatementItem/RuleService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/company/payStatementItem/RuleService.kt new file mode 100644 index 00000000..34a2124d --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/company/payStatementItem/RuleService.kt @@ -0,0 +1,194 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.services.blocking.hris.company.payStatementItem + +import com.google.errorprone.annotations.MustBeClosed +import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleCreateParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleDeleteParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleListPage +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleListParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleUpdateParams +import com.tryfinch.api.models.RuleCreateResponse +import com.tryfinch.api.models.RuleDeleteResponse +import com.tryfinch.api.models.RuleUpdateResponse + +interface RuleService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Custom rules can be created to associate specific attributes to + * pay statement items depending on the use case. For example, pay statement items that meet + * certain conditions can be labeled as a pre-tax 401k. This metadata can be retrieved where pay + * statement item information is available. + */ + fun create(): RuleCreateResponse = create(HrisCompanyPayStatementItemRuleCreateParams.none()) + + /** @see [create] */ + fun create( + params: HrisCompanyPayStatementItemRuleCreateParams = + HrisCompanyPayStatementItemRuleCreateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): RuleCreateResponse + + /** @see [create] */ + fun create( + params: HrisCompanyPayStatementItemRuleCreateParams = + HrisCompanyPayStatementItemRuleCreateParams.none() + ): RuleCreateResponse = create(params, RequestOptions.none()) + + /** @see [create] */ + fun create(requestOptions: RequestOptions): RuleCreateResponse = + create(HrisCompanyPayStatementItemRuleCreateParams.none(), requestOptions) + + /** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Update a rule for a pay statement item. + */ + fun update(params: HrisCompanyPayStatementItemRuleUpdateParams): RuleUpdateResponse = + update(params, RequestOptions.none()) + + /** @see [update] */ + fun update( + params: HrisCompanyPayStatementItemRuleUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): RuleUpdateResponse + + /** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon List all rules of a connection account. + */ + fun list(): HrisCompanyPayStatementItemRuleListPage = + list(HrisCompanyPayStatementItemRuleListParams.none()) + + /** @see [list] */ + fun list( + params: HrisCompanyPayStatementItemRuleListParams = + HrisCompanyPayStatementItemRuleListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HrisCompanyPayStatementItemRuleListPage + + /** @see [list] */ + fun list( + params: HrisCompanyPayStatementItemRuleListParams = + HrisCompanyPayStatementItemRuleListParams.none() + ): HrisCompanyPayStatementItemRuleListPage = list(params, RequestOptions.none()) + + /** @see [list] */ + fun list(requestOptions: RequestOptions): HrisCompanyPayStatementItemRuleListPage = + list(HrisCompanyPayStatementItemRuleListParams.none(), requestOptions) + + /** + * **Beta:** this endpoint currently serves employers onboarded after March 4th and historical + * support will be added soon Delete a rule for a pay statement item. + */ + fun delete(params: HrisCompanyPayStatementItemRuleDeleteParams): RuleDeleteResponse = + delete(params, RequestOptions.none()) + + /** @see [delete] */ + fun delete( + params: HrisCompanyPayStatementItemRuleDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): RuleDeleteResponse + + /** A view of [RuleService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /employer/pay-statement-item/rule`, but is + * otherwise the same as [RuleService.create]. + */ + @MustBeClosed + fun create(): HttpResponseFor = + create(HrisCompanyPayStatementItemRuleCreateParams.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: HrisCompanyPayStatementItemRuleCreateParams = + HrisCompanyPayStatementItemRuleCreateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [create] */ + @MustBeClosed + fun create( + params: HrisCompanyPayStatementItemRuleCreateParams = + HrisCompanyPayStatementItemRuleCreateParams.none() + ): HttpResponseFor = create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create(requestOptions: RequestOptions): HttpResponseFor = + create(HrisCompanyPayStatementItemRuleCreateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /employer/pay-statement-item/rule/{rule_id}`, but is + * otherwise the same as [RuleService.update]. + */ + @MustBeClosed + fun update( + params: HrisCompanyPayStatementItemRuleUpdateParams + ): HttpResponseFor = update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: HrisCompanyPayStatementItemRuleUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /employer/pay-statement-item/rule`, but is otherwise + * the same as [RuleService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = + list(HrisCompanyPayStatementItemRuleListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisCompanyPayStatementItemRuleListParams = + HrisCompanyPayStatementItemRuleListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [list] */ + @MustBeClosed + fun list( + params: HrisCompanyPayStatementItemRuleListParams = + HrisCompanyPayStatementItemRuleListParams.none() + ): HttpResponseFor = + list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + requestOptions: RequestOptions + ): HttpResponseFor = + list(HrisCompanyPayStatementItemRuleListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /employer/pay-statement-item/rule/{rule_id}`, but + * is otherwise the same as [RuleService.delete]. + */ + @MustBeClosed + fun delete( + params: HrisCompanyPayStatementItemRuleDeleteParams + ): HttpResponseFor = delete(params, RequestOptions.none()) + + /** @see [delete] */ + @MustBeClosed + fun delete( + params: HrisCompanyPayStatementItemRuleDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/company/payStatementItem/RuleServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/company/payStatementItem/RuleServiceImpl.kt new file mode 100644 index 00000000..d13e4f22 --- /dev/null +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/hris/company/payStatementItem/RuleServiceImpl.kt @@ -0,0 +1,183 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.services.blocking.hris.company.payStatementItem + +import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.handlers.errorHandler +import com.tryfinch.api.core.handlers.jsonHandler +import com.tryfinch.api.core.handlers.withErrorHandler +import com.tryfinch.api.core.http.HttpMethod +import com.tryfinch.api.core.http.HttpRequest +import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable +import com.tryfinch.api.core.prepare +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleCreateParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleDeleteParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleListPage +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleListParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleUpdateParams +import com.tryfinch.api.models.RuleCreateResponse +import com.tryfinch.api.models.RuleDeleteResponse +import com.tryfinch.api.models.RuleUpdateResponse + +class RuleServiceImpl internal constructor(private val clientOptions: ClientOptions) : RuleService { + + private val withRawResponse: RuleService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): RuleService.WithRawResponse = withRawResponse + + override fun create( + params: HrisCompanyPayStatementItemRuleCreateParams, + requestOptions: RequestOptions, + ): RuleCreateResponse = + // post /employer/pay-statement-item/rule + withRawResponse().create(params, requestOptions).parse() + + override fun update( + params: HrisCompanyPayStatementItemRuleUpdateParams, + requestOptions: RequestOptions, + ): RuleUpdateResponse = + // put /employer/pay-statement-item/rule/{rule_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list( + params: HrisCompanyPayStatementItemRuleListParams, + requestOptions: RequestOptions, + ): HrisCompanyPayStatementItemRuleListPage = + // get /employer/pay-statement-item/rule + withRawResponse().list(params, requestOptions).parse() + + override fun delete( + params: HrisCompanyPayStatementItemRuleDeleteParams, + requestOptions: RequestOptions, + ): RuleDeleteResponse = + // delete /employer/pay-statement-item/rule/{rule_id} + withRawResponse().delete(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + RuleService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun create( + params: HrisCompanyPayStatementItemRuleCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("employer", "pay-statement-item", "rule") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun update( + params: HrisCompanyPayStatementItemRuleUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .addPathSegments("employer", "pay-statement-item", "rule", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun list( + params: HrisCompanyPayStatementItemRuleListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "pay-statement-item", "rule") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + HrisCompanyPayStatementItemRuleListPage.of( + RuleServiceImpl(clientOptions), + params, + it, + ) + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun delete( + params: HrisCompanyPayStatementItemRuleDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .addPathSegments("employer", "pay-statement-item", "rule", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/AutomatedService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/AutomatedService.kt index 1755269a..fafcfff9 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/AutomatedService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/AutomatedService.kt @@ -1,19 +1,24 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.jobs +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.AutomatedAsyncJob import com.tryfinch.api.models.AutomatedCreateResponse +import com.tryfinch.api.models.AutomatedListResponse import com.tryfinch.api.models.JobAutomatedCreateParams -import com.tryfinch.api.models.JobAutomatedListPage import com.tryfinch.api.models.JobAutomatedListParams import com.tryfinch.api.models.JobAutomatedRetrieveParams interface AutomatedService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** * Enqueue an automated job. * @@ -29,32 +34,28 @@ interface AutomatedService { * This endpoint is available for _Scale_ tier customers as an add-on. To request access to this * endpoint, please contact your Finch account manager. */ - @JvmOverloads + fun create(): AutomatedCreateResponse = create(JobAutomatedCreateParams.none()) + + /** @see [create] */ fun create( params: JobAutomatedCreateParams = JobAutomatedCreateParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): AutomatedCreateResponse - /** - * Enqueue an automated job. - * - * `data_sync_all`: Enqueue a job to re-sync all data for a connection. `data_sync_all` has a - * concurrency limit of 1 job at a time per connection. This means that if this endpoint is - * called while a job is already in progress for this connection, Finch will return the `job_id` - * of the job that is currently in progress. Finch allows a fixed window rate limit of 1 forced - * refresh per hour per connection. - * - * `w4_form_employee_sync`: Enqueues a job for sync W-4 data for a particular individual, - * identified by `individual_id`. This feature is currently in beta. - * - * This endpoint is available for _Scale_ tier customers as an add-on. To request access to this - * endpoint, please contact your Finch account manager. - */ + /** @see [create] */ + fun create( + params: JobAutomatedCreateParams = JobAutomatedCreateParams.none() + ): AutomatedCreateResponse = create(params, RequestOptions.none()) + + /** @see [create] */ fun create(requestOptions: RequestOptions): AutomatedCreateResponse = create(JobAutomatedCreateParams.none(), requestOptions) /** Get an automated job by `job_id`. */ - @JvmOverloads + fun retrieve(params: JobAutomatedRetrieveParams): AutomatedAsyncJob = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ fun retrieve( params: JobAutomatedRetrieveParams, requestOptions: RequestOptions = RequestOptions.none(), @@ -65,17 +66,90 @@ interface AutomatedService { * sorted in descending order by submission time. For scheduled jobs such as data syncs, only * the next scheduled job is shown. */ - @JvmOverloads + fun list(): AutomatedListResponse = list(JobAutomatedListParams.none()) + + /** @see [list] */ fun list( params: JobAutomatedListParams = JobAutomatedListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): JobAutomatedListPage + ): AutomatedListResponse - /** - * Get all automated jobs. Automated jobs are completed by a machine. By default, jobs are - * sorted in descending order by submission time. For scheduled jobs such as data syncs, only - * the next scheduled job is shown. - */ - fun list(requestOptions: RequestOptions): JobAutomatedListPage = + /** @see [list] */ + fun list( + params: JobAutomatedListParams = JobAutomatedListParams.none() + ): AutomatedListResponse = list(params, RequestOptions.none()) + + /** @see [list] */ + fun list(requestOptions: RequestOptions): AutomatedListResponse = list(JobAutomatedListParams.none(), requestOptions) + + /** A view of [AutomatedService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /jobs/automated`, but is otherwise the same as + * [AutomatedService.create]. + */ + @MustBeClosed + fun create(): HttpResponseFor = + create(JobAutomatedCreateParams.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: JobAutomatedCreateParams = JobAutomatedCreateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [create] */ + @MustBeClosed + fun create( + params: JobAutomatedCreateParams = JobAutomatedCreateParams.none() + ): HttpResponseFor = create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create(requestOptions: RequestOptions): HttpResponseFor = + create(JobAutomatedCreateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /jobs/automated/{job_id}`, but is otherwise the same + * as [AutomatedService.retrieve]. + */ + @MustBeClosed + fun retrieve(params: JobAutomatedRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: JobAutomatedRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /jobs/automated`, but is otherwise the same as + * [AutomatedService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(JobAutomatedListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: JobAutomatedListParams = JobAutomatedListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [list] */ + @MustBeClosed + fun list( + params: JobAutomatedListParams = JobAutomatedListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(JobAutomatedListParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/AutomatedServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/AutomatedServiceImpl.kt index 89ff745a..3d20fb5e 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/AutomatedServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/AutomatedServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.jobs import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,112 +11,131 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.AutomatedAsyncJob import com.tryfinch.api.models.AutomatedCreateResponse +import com.tryfinch.api.models.AutomatedListResponse import com.tryfinch.api.models.JobAutomatedCreateParams -import com.tryfinch.api.models.JobAutomatedListPage import com.tryfinch.api.models.JobAutomatedListParams import com.tryfinch.api.models.JobAutomatedRetrieveParams class AutomatedServiceImpl internal constructor(private val clientOptions: ClientOptions) : AutomatedService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) - - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * Enqueue an automated job. - * - * `data_sync_all`: Enqueue a job to re-sync all data for a connection. `data_sync_all` has a - * concurrency limit of 1 job at a time per connection. This means that if this endpoint is - * called while a job is already in progress for this connection, Finch will return the `job_id` - * of the job that is currently in progress. Finch allows a fixed window rate limit of 1 forced - * refresh per hour per connection. - * - * `w4_form_employee_sync`: Enqueues a job for sync W-4 data for a particular individual, - * identified by `individual_id`. This feature is currently in beta. - * - * This endpoint is available for _Scale_ tier customers as an add-on. To request access to this - * endpoint, please contact your Finch account manager. - */ + private val withRawResponse: AutomatedService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): AutomatedService.WithRawResponse = withRawResponse + override fun create( params: JobAutomatedCreateParams, requestOptions: RequestOptions, - ): AutomatedCreateResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("jobs", "automated") - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): AutomatedCreateResponse = + // post /jobs/automated + withRawResponse().create(params, requestOptions).parse() - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Get an automated job by `job_id`. */ override fun retrieve( params: JobAutomatedRetrieveParams, requestOptions: RequestOptions, - ): AutomatedAsyncJob { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("jobs", "automated", params.getPathParam(0)) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { retrieveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): AutomatedAsyncJob = + // get /jobs/automated/{job_id} + withRawResponse().retrieve(params, requestOptions).parse() - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * Get all automated jobs. Automated jobs are completed by a machine. By default, jobs are - * sorted in descending order by submission time. For scheduled jobs such as data syncs, only - * the next scheduled job is shown. - */ override fun list( params: JobAutomatedListParams, requestOptions: RequestOptions, - ): JobAutomatedListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("jobs", "automated") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): AutomatedListResponse = + // get /jobs/automated + withRawResponse().list(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AutomatedService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: JobAutomatedCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("jobs", "automated") + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun retrieve( + params: JobAutomatedRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("jobs", "automated", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun list( + params: JobAutomatedListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("jobs", "automated") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - .let { JobAutomatedListPage.of(this, params, it) } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/ManualService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/ManualService.kt index b6b76e59..66de50ae 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/ManualService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/ManualService.kt @@ -1,22 +1,49 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.jobs +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.JobManualRetrieveParams import com.tryfinch.api.models.ManualAsyncJob interface ManualService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** * Get a manual job by `job_id`. Manual jobs are completed by a human and include Assisted * Benefits jobs. */ - @JvmOverloads + fun retrieve(params: JobManualRetrieveParams): ManualAsyncJob = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ fun retrieve( params: JobManualRetrieveParams, requestOptions: RequestOptions = RequestOptions.none(), ): ManualAsyncJob + + /** A view of [ManualService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /jobs/manual/{job_id}`, but is otherwise the same as + * [ManualService.retrieve]. + */ + @MustBeClosed + fun retrieve(params: JobManualRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: JobManualRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/ManualServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/ManualServiceImpl.kt index 9ce1917a..b055b8e6 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/ManualServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/jobs/ManualServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.jobs import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,40 +11,57 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.JobManualRetrieveParams import com.tryfinch.api.models.ManualAsyncJob class ManualServiceImpl internal constructor(private val clientOptions: ClientOptions) : ManualService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ManualService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): ManualService.WithRawResponse = withRawResponse - /** - * Get a manual job by `job_id`. Manual jobs are completed by a human and include Assisted - * Benefits jobs. - */ override fun retrieve( params: JobManualRetrieveParams, requestOptions: RequestOptions, - ): ManualAsyncJob { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("jobs", "manual", params.getPathParam(0)) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { retrieveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): ManualAsyncJob = + // get /jobs/manual/{job_id} + withRawResponse().retrieve(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ManualService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun retrieve( + params: JobManualRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("jobs", "manual", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/payroll/PayGroupService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/payroll/PayGroupService.kt index b5c0e37b..dfbd5bb3 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/payroll/PayGroupService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/payroll/PayGroupService.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.payroll +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.PayGroupRetrieveResponse import com.tryfinch.api.models.PayrollPayGroupListPage import com.tryfinch.api.models.PayrollPayGroupListParams @@ -12,21 +12,82 @@ import com.tryfinch.api.models.PayrollPayGroupRetrieveParams interface PayGroupService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Read information from a single pay group */ - @JvmOverloads + fun retrieve(params: PayrollPayGroupRetrieveParams): PayGroupRetrieveResponse = + retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ fun retrieve( params: PayrollPayGroupRetrieveParams, requestOptions: RequestOptions = RequestOptions.none(), ): PayGroupRetrieveResponse /** Read company pay groups and frequencies */ - @JvmOverloads + fun list(): PayrollPayGroupListPage = list(PayrollPayGroupListParams.none()) + + /** @see [list] */ fun list( params: PayrollPayGroupListParams = PayrollPayGroupListParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): PayrollPayGroupListPage - /** Read company pay groups and frequencies */ + /** @see [list] */ + fun list( + params: PayrollPayGroupListParams = PayrollPayGroupListParams.none() + ): PayrollPayGroupListPage = list(params, RequestOptions.none()) + + /** @see [list] */ fun list(requestOptions: RequestOptions): PayrollPayGroupListPage = list(PayrollPayGroupListParams.none(), requestOptions) + + /** A view of [PayGroupService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /employer/pay-groups/{pay_group_id}`, but is + * otherwise the same as [PayGroupService.retrieve]. + */ + @MustBeClosed + fun retrieve( + params: PayrollPayGroupRetrieveParams + ): HttpResponseFor = retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: PayrollPayGroupRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /employer/pay-groups`, but is otherwise the same as + * [PayGroupService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = + list(PayrollPayGroupListParams.none()) + + /** @see [list] */ + @MustBeClosed + fun list( + params: PayrollPayGroupListParams = PayrollPayGroupListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [list] */ + @MustBeClosed + fun list( + params: PayrollPayGroupListParams = PayrollPayGroupListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see [list] */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(PayrollPayGroupListParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/payroll/PayGroupServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/payroll/PayGroupServiceImpl.kt index f4653cda..92c6cbcc 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/payroll/PayGroupServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/payroll/PayGroupServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.payroll import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,8 +11,9 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.PayGroupListResponse import com.tryfinch.api.models.PayGroupRetrieveResponse import com.tryfinch.api.models.PayrollPayGroupListPage @@ -21,62 +23,90 @@ import com.tryfinch.api.models.PayrollPayGroupRetrieveParams class PayGroupServiceImpl internal constructor(private val clientOptions: ClientOptions) : PayGroupService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: PayGroupService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): PayGroupService.WithRawResponse = withRawResponse - /** Read information from a single pay group */ override fun retrieve( params: PayrollPayGroupRetrieveParams, requestOptions: RequestOptions, - ): PayGroupRetrieveResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "pay-groups", params.getPathParam(0)) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { retrieveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): PayGroupRetrieveResponse = + // get /employer/pay-groups/{pay_group_id} + withRawResponse().retrieve(params, requestOptions).parse() - private val listHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Read company pay groups and frequencies */ override fun list( params: PayrollPayGroupListParams, requestOptions: RequestOptions, - ): PayrollPayGroupListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("employer", "pay-groups") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { listHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } + ): PayrollPayGroupListPage = + // get /employer/pay-groups + withRawResponse().list(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PayGroupService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retrieve( + params: PayrollPayGroupRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "pay-groups", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } - .let { - PayrollPayGroupListPage.of( - this, - params, - PayrollPayGroupListPage.Response.builder().items(it).build(), - ) + } + + private val listHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun list( + params: PayrollPayGroupListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("employer", "pay-groups") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + .let { + PayrollPayGroupListPage.of( + PayGroupServiceImpl(clientOptions), + params, + PayrollPayGroupListPage.Response.builder().items(it).build(), + ) + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/CompanyService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/CompanyService.kt index 7c7c7238..c2f4eaf2 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/CompanyService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/CompanyService.kt @@ -1,19 +1,46 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.sandbox +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.CompanyUpdateResponse import com.tryfinch.api.models.SandboxCompanyUpdateParams interface CompanyService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Update a sandbox company's data */ - @JvmOverloads + fun update(params: SandboxCompanyUpdateParams): CompanyUpdateResponse = + update(params, RequestOptions.none()) + + /** @see [update] */ fun update( params: SandboxCompanyUpdateParams, requestOptions: RequestOptions = RequestOptions.none(), ): CompanyUpdateResponse + + /** A view of [CompanyService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `put /sandbox/company`, but is otherwise the same as + * [CompanyService.update]. + */ + @MustBeClosed + fun update(params: SandboxCompanyUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: SandboxCompanyUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/CompanyServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/CompanyServiceImpl.kt index 63e3b740..6289d961 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/CompanyServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/CompanyServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.sandbox import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,39 +11,60 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.CompanyUpdateResponse import com.tryfinch.api.models.SandboxCompanyUpdateParams class CompanyServiceImpl internal constructor(private val clientOptions: ClientOptions) : CompanyService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: CompanyService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): CompanyService.WithRawResponse = withRawResponse - /** Update a sandbox company's data */ override fun update( params: SandboxCompanyUpdateParams, requestOptions: RequestOptions, - ): CompanyUpdateResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("sandbox", "company") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): CompanyUpdateResponse = + // put /sandbox/company + withRawResponse().update(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + CompanyService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun update( + params: SandboxCompanyUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .addPathSegments("sandbox", "company") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/ConnectionService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/ConnectionService.kt index c1bca965..7d3ce2c5 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/ConnectionService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/ConnectionService.kt @@ -1,22 +1,52 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.sandbox +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.ConnectionCreateResponse import com.tryfinch.api.models.SandboxConnectionCreateParams import com.tryfinch.api.services.blocking.sandbox.connections.AccountService interface ConnectionService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun accounts(): AccountService /** Create a new connection (new company/provider pair) with a new account */ - @JvmOverloads + fun create(params: SandboxConnectionCreateParams): ConnectionCreateResponse = + create(params, RequestOptions.none()) + + /** @see [create] */ fun create( params: SandboxConnectionCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): ConnectionCreateResponse + + /** A view of [ConnectionService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun accounts(): AccountService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /sandbox/connections`, but is otherwise the same as + * [ConnectionService.create]. + */ + @MustBeClosed + fun create( + params: SandboxConnectionCreateParams + ): HttpResponseFor = create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxConnectionCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/ConnectionServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/ConnectionServiceImpl.kt index 8f8fdd38..18e96822 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/ConnectionServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/ConnectionServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.sandbox import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.ConnectionCreateResponse import com.tryfinch.api.models.SandboxConnectionCreateParams import com.tryfinch.api.services.blocking.sandbox.connections.AccountService @@ -21,35 +23,60 @@ import com.tryfinch.api.services.blocking.sandbox.connections.AccountServiceImpl class ConnectionServiceImpl internal constructor(private val clientOptions: ClientOptions) : ConnectionService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ConnectionService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } private val accounts: AccountService by lazy { AccountServiceImpl(clientOptions) } - override fun accounts(): AccountService = accounts + override fun withRawResponse(): ConnectionService.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun accounts(): AccountService = accounts - /** Create a new connection (new company/provider pair) with a new account */ override fun create( params: SandboxConnectionCreateParams, requestOptions: RequestOptions, - ): ConnectionCreateResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("sandbox", "connections") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): ConnectionCreateResponse = + // post /sandbox/connections + withRawResponse().create(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ConnectionService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val accounts: AccountService.WithRawResponse by lazy { + AccountServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun accounts(): AccountService.WithRawResponse = accounts + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: SandboxConnectionCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("sandbox", "connections") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/DirectoryService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/DirectoryService.kt index 210e1395..afe8fbc5 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/DirectoryService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/DirectoryService.kt @@ -1,23 +1,65 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.sandbox -import com.tryfinch.api.core.JsonValue +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.models.DirectoryCreateResponse import com.tryfinch.api.models.SandboxDirectoryCreateParams interface DirectoryService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Add new individuals to a sandbox company */ - @JvmOverloads + fun create(): List = create(SandboxDirectoryCreateParams.none()) + + /** @see [create] */ fun create( params: SandboxDirectoryCreateParams = SandboxDirectoryCreateParams.none(), requestOptions: RequestOptions = RequestOptions.none(), - ): List + ): List - /** Add new individuals to a sandbox company */ - fun create(requestOptions: RequestOptions): List = + /** @see [create] */ + fun create( + params: SandboxDirectoryCreateParams = SandboxDirectoryCreateParams.none() + ): List = create(params, RequestOptions.none()) + + /** @see [create] */ + fun create(requestOptions: RequestOptions): List = create(SandboxDirectoryCreateParams.none(), requestOptions) + + /** A view of [DirectoryService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /sandbox/directory`, but is otherwise the same as + * [DirectoryService.create]. + */ + @MustBeClosed + fun create(): HttpResponseFor> = + create(SandboxDirectoryCreateParams.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxDirectoryCreateParams = SandboxDirectoryCreateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor> + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxDirectoryCreateParams = SandboxDirectoryCreateParams.none() + ): HttpResponseFor> = create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create(requestOptions: RequestOptions): HttpResponseFor> = + create(SandboxDirectoryCreateParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/DirectoryServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/DirectoryServiceImpl.kt index acc30e28..41ad5a2f 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/DirectoryServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/DirectoryServiceImpl.kt @@ -11,32 +11,60 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError +import com.tryfinch.api.models.DirectoryCreateResponse import com.tryfinch.api.models.SandboxDirectoryCreateParams class DirectoryServiceImpl internal constructor(private val clientOptions: ClientOptions) : DirectoryService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: DirectoryService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val createHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): DirectoryService.WithRawResponse = withRawResponse - /** Add new individuals to a sandbox company */ override fun create( params: SandboxDirectoryCreateParams, requestOptions: RequestOptions, - ): List { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("sandbox", "directory") - .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response.use { createHandler.handle(it) } + ): List = + // post /sandbox/directory + withRawResponse().create(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + DirectoryService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: SandboxDirectoryCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("sandbox", "directory") + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/EmploymentService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/EmploymentService.kt index 6d26b611..d1af16fb 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/EmploymentService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/EmploymentService.kt @@ -1,19 +1,47 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.sandbox +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.EmploymentUpdateResponse import com.tryfinch.api.models.SandboxEmploymentUpdateParams interface EmploymentService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Update sandbox employment */ - @JvmOverloads + fun update(params: SandboxEmploymentUpdateParams): EmploymentUpdateResponse = + update(params, RequestOptions.none()) + + /** @see [update] */ fun update( params: SandboxEmploymentUpdateParams, requestOptions: RequestOptions = RequestOptions.none(), ): EmploymentUpdateResponse + + /** A view of [EmploymentService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `put /sandbox/employment/{individual_id}`, but is + * otherwise the same as [EmploymentService.update]. + */ + @MustBeClosed + fun update( + params: SandboxEmploymentUpdateParams + ): HttpResponseFor = update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: SandboxEmploymentUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/EmploymentServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/EmploymentServiceImpl.kt index a538224d..da766444 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/EmploymentServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/EmploymentServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.sandbox import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,40 +11,60 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.EmploymentUpdateResponse import com.tryfinch.api.models.SandboxEmploymentUpdateParams class EmploymentServiceImpl internal constructor(private val clientOptions: ClientOptions) : EmploymentService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: EmploymentService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): EmploymentService.WithRawResponse = withRawResponse - /** Update sandbox employment */ override fun update( params: SandboxEmploymentUpdateParams, requestOptions: RequestOptions, - ): EmploymentUpdateResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("sandbox", "employment", params.getPathParam(0)) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): EmploymentUpdateResponse = + // put /sandbox/employment/{individual_id} + withRawResponse().update(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + EmploymentService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun update( + params: SandboxEmploymentUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .addPathSegments("sandbox", "employment", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/IndividualService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/IndividualService.kt index 34657b8f..8be711cb 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/IndividualService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/IndividualService.kt @@ -1,19 +1,47 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.sandbox +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.IndividualUpdateResponse import com.tryfinch.api.models.SandboxIndividualUpdateParams interface IndividualService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Update sandbox individual */ - @JvmOverloads + fun update(params: SandboxIndividualUpdateParams): IndividualUpdateResponse = + update(params, RequestOptions.none()) + + /** @see [update] */ fun update( params: SandboxIndividualUpdateParams, requestOptions: RequestOptions = RequestOptions.none(), ): IndividualUpdateResponse + + /** A view of [IndividualService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `put /sandbox/individual/{individual_id}`, but is + * otherwise the same as [IndividualService.update]. + */ + @MustBeClosed + fun update( + params: SandboxIndividualUpdateParams + ): HttpResponseFor = update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: SandboxIndividualUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/IndividualServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/IndividualServiceImpl.kt index feb15e1f..0570df24 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/IndividualServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/IndividualServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.sandbox import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,40 +11,60 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.IndividualUpdateResponse import com.tryfinch.api.models.SandboxIndividualUpdateParams class IndividualServiceImpl internal constructor(private val clientOptions: ClientOptions) : IndividualService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: IndividualService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): IndividualService.WithRawResponse = withRawResponse - /** Update sandbox individual */ override fun update( params: SandboxIndividualUpdateParams, requestOptions: RequestOptions, - ): IndividualUpdateResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("sandbox", "individual", params.getPathParam(0)) - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): IndividualUpdateResponse = + // put /sandbox/individual/{individual_id} + withRawResponse().update(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + IndividualService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun update( + params: SandboxIndividualUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .addPathSegments("sandbox", "individual", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/JobService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/JobService.kt index 65e3c055..cbff8247 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/JobService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/JobService.kt @@ -1,22 +1,51 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.sandbox +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.JobCreateResponse import com.tryfinch.api.models.SandboxJobCreateParams import com.tryfinch.api.services.blocking.sandbox.jobs.ConfigurationService interface JobService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + fun configuration(): ConfigurationService /** Enqueue a new sandbox job */ - @JvmOverloads + fun create(params: SandboxJobCreateParams): JobCreateResponse = + create(params, RequestOptions.none()) + + /** @see [create] */ fun create( params: SandboxJobCreateParams, requestOptions: RequestOptions = RequestOptions.none(), ): JobCreateResponse + + /** A view of [JobService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + fun configuration(): ConfigurationService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /sandbox/jobs`, but is otherwise the same as + * [JobService.create]. + */ + @MustBeClosed + fun create(params: SandboxJobCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxJobCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/JobServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/JobServiceImpl.kt index a2a60c9d..5a01752f 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/JobServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/JobServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.sandbox import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.JobCreateResponse import com.tryfinch.api.models.SandboxJobCreateParams import com.tryfinch.api.services.blocking.sandbox.jobs.ConfigurationService @@ -20,36 +22,61 @@ import com.tryfinch.api.services.blocking.sandbox.jobs.ConfigurationServiceImpl class JobServiceImpl internal constructor(private val clientOptions: ClientOptions) : JobService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: JobService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } private val configuration: ConfigurationService by lazy { ConfigurationServiceImpl(clientOptions) } - override fun configuration(): ConfigurationService = configuration + override fun withRawResponse(): JobService.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun configuration(): ConfigurationService = configuration - /** Enqueue a new sandbox job */ override fun create( params: SandboxJobCreateParams, requestOptions: RequestOptions, - ): JobCreateResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("sandbox", "jobs") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): JobCreateResponse = + // post /sandbox/jobs + withRawResponse().create(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + JobService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val configuration: ConfigurationService.WithRawResponse by lazy { + ConfigurationServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun configuration(): ConfigurationService.WithRawResponse = configuration + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + override fun create( + params: SandboxJobCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("sandbox", "jobs") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/PaymentService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/PaymentService.kt index 6e20efa2..5f78f493 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/PaymentService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/PaymentService.kt @@ -1,23 +1,65 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.sandbox +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.PaymentCreateResponse import com.tryfinch.api.models.SandboxPaymentCreateParams interface PaymentService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Add a new sandbox payment */ - @JvmOverloads + fun create(): PaymentCreateResponse = create(SandboxPaymentCreateParams.none()) + + /** @see [create] */ fun create( params: SandboxPaymentCreateParams = SandboxPaymentCreateParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): PaymentCreateResponse - /** Add a new sandbox payment */ + /** @see [create] */ + fun create( + params: SandboxPaymentCreateParams = SandboxPaymentCreateParams.none() + ): PaymentCreateResponse = create(params, RequestOptions.none()) + + /** @see [create] */ fun create(requestOptions: RequestOptions): PaymentCreateResponse = create(SandboxPaymentCreateParams.none(), requestOptions) + + /** A view of [PaymentService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /sandbox/payment`, but is otherwise the same as + * [PaymentService.create]. + */ + @MustBeClosed + fun create(): HttpResponseFor = + create(SandboxPaymentCreateParams.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxPaymentCreateParams = SandboxPaymentCreateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxPaymentCreateParams = SandboxPaymentCreateParams.none() + ): HttpResponseFor = create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create(requestOptions: RequestOptions): HttpResponseFor = + create(SandboxPaymentCreateParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/PaymentServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/PaymentServiceImpl.kt index 61b5783b..efcd8f16 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/PaymentServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/PaymentServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.sandbox import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,39 +11,60 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.PaymentCreateResponse import com.tryfinch.api.models.SandboxPaymentCreateParams class PaymentServiceImpl internal constructor(private val clientOptions: ClientOptions) : PaymentService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: PaymentService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): PaymentService.WithRawResponse = withRawResponse - /** Add a new sandbox payment */ override fun create( params: SandboxPaymentCreateParams, requestOptions: RequestOptions, - ): PaymentCreateResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("sandbox", "payment") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): PaymentCreateResponse = + // post /sandbox/payment + withRawResponse().create(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PaymentService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: SandboxPaymentCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("sandbox", "payment") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/connections/AccountService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/connections/AccountService.kt index a2c8266f..205880de 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/connections/AccountService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/connections/AccountService.kt @@ -1,10 +1,10 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.sandbox.connections +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.AccountCreateResponse import com.tryfinch.api.models.AccountUpdateResponse import com.tryfinch.api.models.SandboxConnectionAccountCreateParams @@ -12,8 +12,16 @@ import com.tryfinch.api.models.SandboxConnectionAccountUpdateParams interface AccountService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Create a new account for an existing connection (company/provider pair) */ - @JvmOverloads + fun create(params: SandboxConnectionAccountCreateParams): AccountCreateResponse = + create(params, RequestOptions.none()) + + /** @see [create] */ fun create( params: SandboxConnectionAccountCreateParams, requestOptions: RequestOptions = RequestOptions.none(), @@ -23,16 +31,68 @@ interface AccountService { * Update an existing sandbox account. Change the connection status to understand how the Finch * API responds. */ - @JvmOverloads + fun update(): AccountUpdateResponse = update(SandboxConnectionAccountUpdateParams.none()) + + /** @see [update] */ fun update( params: SandboxConnectionAccountUpdateParams = SandboxConnectionAccountUpdateParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): AccountUpdateResponse - /** - * Update an existing sandbox account. Change the connection status to understand how the Finch - * API responds. - */ + /** @see [update] */ + fun update( + params: SandboxConnectionAccountUpdateParams = SandboxConnectionAccountUpdateParams.none() + ): AccountUpdateResponse = update(params, RequestOptions.none()) + + /** @see [update] */ fun update(requestOptions: RequestOptions): AccountUpdateResponse = update(SandboxConnectionAccountUpdateParams.none(), requestOptions) + + /** A view of [AccountService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `post /sandbox/connections/accounts`, but is otherwise + * the same as [AccountService.create]. + */ + @MustBeClosed + fun create( + params: SandboxConnectionAccountCreateParams + ): HttpResponseFor = create(params, RequestOptions.none()) + + /** @see [create] */ + @MustBeClosed + fun create( + params: SandboxConnectionAccountCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `put /sandbox/connections/accounts`, but is otherwise the + * same as [AccountService.update]. + */ + @MustBeClosed + fun update(): HttpResponseFor = + update(SandboxConnectionAccountUpdateParams.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: SandboxConnectionAccountUpdateParams = + SandboxConnectionAccountUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see [update] */ + @MustBeClosed + fun update( + params: SandboxConnectionAccountUpdateParams = + SandboxConnectionAccountUpdateParams.none() + ): HttpResponseFor = update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update(requestOptions: RequestOptions): HttpResponseFor = + update(SandboxConnectionAccountUpdateParams.none(), requestOptions) + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/connections/AccountServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/connections/AccountServiceImpl.kt index 6f053eb8..12f7aeb6 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/connections/AccountServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/connections/AccountServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.sandbox.connections import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.AccountCreateResponse import com.tryfinch.api.models.AccountUpdateResponse import com.tryfinch.api.models.SandboxConnectionAccountCreateParams @@ -21,58 +23,85 @@ import com.tryfinch.api.models.SandboxConnectionAccountUpdateParams class AccountServiceImpl internal constructor(private val clientOptions: ClientOptions) : AccountService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: AccountService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withRawResponse(): AccountService.WithRawResponse = withRawResponse - /** Create a new account for an existing connection (company/provider pair) */ override fun create( params: SandboxConnectionAccountCreateParams, requestOptions: RequestOptions, - ): AccountCreateResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("sandbox", "connections", "accounts") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { createHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } - } - } + ): AccountCreateResponse = + // post /sandbox/connections/accounts + withRawResponse().create(params, requestOptions).parse() - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Update an existing sandbox account. Change the connection status to understand how the Finch - * API responds. - */ override fun update( params: SandboxConnectionAccountUpdateParams, requestOptions: RequestOptions, - ): AccountUpdateResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("sandbox", "connections", "accounts") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): AccountUpdateResponse = + // put /sandbox/connections/accounts + withRawResponse().update(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AccountService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun create( + params: SandboxConnectionAccountCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("sandbox", "connections", "accounts") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun update( + params: SandboxConnectionAccountUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .addPathSegments("sandbox", "connections", "accounts") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/jobs/ConfigurationService.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/jobs/ConfigurationService.kt index 4dfb7f1b..d9fa6264 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/jobs/ConfigurationService.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/jobs/ConfigurationService.kt @@ -1,32 +1,100 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.tryfinch.api.services.blocking.sandbox.jobs +import com.google.errorprone.annotations.MustBeClosed import com.tryfinch.api.core.RequestOptions +import com.tryfinch.api.core.http.HttpResponseFor import com.tryfinch.api.models.SandboxJobConfiguration import com.tryfinch.api.models.SandboxJobConfigurationRetrieveParams import com.tryfinch.api.models.SandboxJobConfigurationUpdateParams interface ConfigurationService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + /** Get configurations for sandbox jobs */ - @JvmOverloads + fun retrieve(): List = + retrieve(SandboxJobConfigurationRetrieveParams.none()) + + /** @see [retrieve] */ fun retrieve( params: SandboxJobConfigurationRetrieveParams = SandboxJobConfigurationRetrieveParams.none(), requestOptions: RequestOptions = RequestOptions.none(), ): List - /** Get configurations for sandbox jobs */ + /** @see [retrieve] */ + fun retrieve( + params: SandboxJobConfigurationRetrieveParams = SandboxJobConfigurationRetrieveParams.none() + ): List = retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ fun retrieve(requestOptions: RequestOptions): List = retrieve(SandboxJobConfigurationRetrieveParams.none(), requestOptions) /** Update configurations for sandbox jobs */ - @JvmOverloads + fun update(params: SandboxJobConfigurationUpdateParams): SandboxJobConfiguration = + update(params, RequestOptions.none()) + + /** @see [update] */ fun update( params: SandboxJobConfigurationUpdateParams, requestOptions: RequestOptions = RequestOptions.none(), ): SandboxJobConfiguration + + /** + * A view of [ConfigurationService] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a raw HTTP response for `get /sandbox/jobs/configuration`, but is otherwise the + * same as [ConfigurationService.retrieve]. + */ + @MustBeClosed + fun retrieve(): HttpResponseFor> = + retrieve(SandboxJobConfigurationRetrieveParams.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: SandboxJobConfigurationRetrieveParams = + SandboxJobConfigurationRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor> + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + params: SandboxJobConfigurationRetrieveParams = + SandboxJobConfigurationRetrieveParams.none() + ): HttpResponseFor> = retrieve(params, RequestOptions.none()) + + /** @see [retrieve] */ + @MustBeClosed + fun retrieve( + requestOptions: RequestOptions + ): HttpResponseFor> = + retrieve(SandboxJobConfigurationRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /sandbox/jobs/configuration`, but is otherwise the + * same as [ConfigurationService.update]. + */ + @MustBeClosed + fun update( + params: SandboxJobConfigurationUpdateParams + ): HttpResponseFor = update(params, RequestOptions.none()) + + /** @see [update] */ + @MustBeClosed + fun update( + params: SandboxJobConfigurationUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } } diff --git a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/jobs/ConfigurationServiceImpl.kt b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/jobs/ConfigurationServiceImpl.kt index 08046405..ce53138b 100644 --- a/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/jobs/ConfigurationServiceImpl.kt +++ b/finch-java-core/src/main/kotlin/com/tryfinch/api/services/blocking/sandbox/jobs/ConfigurationServiceImpl.kt @@ -3,6 +3,7 @@ package com.tryfinch.api.services.blocking.sandbox.jobs import com.tryfinch.api.core.ClientOptions +import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.RequestOptions import com.tryfinch.api.core.handlers.errorHandler import com.tryfinch.api.core.handlers.jsonHandler @@ -10,9 +11,10 @@ import com.tryfinch.api.core.handlers.withErrorHandler import com.tryfinch.api.core.http.HttpMethod import com.tryfinch.api.core.http.HttpRequest import com.tryfinch.api.core.http.HttpResponse.Handler -import com.tryfinch.api.core.json +import com.tryfinch.api.core.http.HttpResponseFor +import com.tryfinch.api.core.http.json +import com.tryfinch.api.core.http.parseable import com.tryfinch.api.core.prepare -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.models.SandboxJobConfiguration import com.tryfinch.api.models.SandboxJobConfigurationRetrieveParams import com.tryfinch.api.models.SandboxJobConfigurationUpdateParams @@ -20,56 +22,84 @@ import com.tryfinch.api.models.SandboxJobConfigurationUpdateParams class ConfigurationServiceImpl internal constructor(private val clientOptions: ClientOptions) : ConfigurationService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ConfigurationService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val retrieveHandler: Handler> = - jsonHandler>(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + override fun withRawResponse(): ConfigurationService.WithRawResponse = withRawResponse - /** Get configurations for sandbox jobs */ override fun retrieve( params: SandboxJobConfigurationRetrieveParams, requestOptions: RequestOptions, - ): List { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("sandbox", "jobs", "configuration") - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { retrieveHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.forEach { it.validate() } - } - } - } + ): List = + // get /sandbox/jobs/configuration + withRawResponse().retrieve(params, requestOptions).parse() - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Update configurations for sandbox jobs */ override fun update( params: SandboxJobConfigurationUpdateParams, requestOptions: RequestOptions, - ): SandboxJobConfiguration { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("sandbox", "jobs", "configuration") - .body(json(clientOptions.jsonMapper, params._body())) - .build() - .prepare(clientOptions, params) - val response = clientOptions.httpClient.execute(request, requestOptions) - return response - .use { updateHandler.handle(it) } - .also { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - it.validate() - } + ): SandboxJobConfiguration = + // put /sandbox/jobs/configuration + withRawResponse().update(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ConfigurationService.WithRawResponse { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun retrieve( + params: SandboxJobConfigurationRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("sandbox", "jobs", "configuration") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.forEach { it.validate() } + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + override fun update( + params: SandboxJobConfigurationUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .addPathSegments("sandbox", "jobs", "configuration") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return response.parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } + } } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/core/ObjectMappersTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/core/ObjectMappersTest.kt new file mode 100644 index 00000000..75309d20 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/core/ObjectMappersTest.kt @@ -0,0 +1,102 @@ +package com.tryfinch.api.core + +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.exc.MismatchedInputException +import com.fasterxml.jackson.module.kotlin.readValue +import java.time.LocalDateTime +import kotlin.reflect.KClass +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.catchThrowable +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertDoesNotThrow +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource +import org.junitpioneer.jupiter.cartesian.CartesianTest + +internal class ObjectMappersTest { + + internal class ClassWithBooleanFieldPrefixedWithIs(private val isActive: JsonField) { + + @JsonProperty("is_active") @ExcludeMissing fun _isActive() = isActive + } + + @Test + fun write_whenFieldPrefixedWithIs_keepsPrefix() { + val value = ClassWithBooleanFieldPrefixedWithIs(JsonField.of(true)) + + val json = jsonMapper().writeValueAsString(value) + + assertThat(json).isEqualTo("{\"is_active\":true}") + } + + internal class Class(@get:JsonProperty("field") @JsonProperty("field") val field: String) + + enum class ShapeTestCase(val value: Any, val kClass: KClass<*>) { + STRING("Hello World!", String::class), + BOOLEAN(true, Boolean::class), + FLOAT(3.14F, Float::class), + DOUBLE(3.14, Double::class), + INTEGER(42, Int::class), + LONG(42L, Long::class), + MAP(mapOf("property" to "value"), Map::class), + CLASS(Class("Hello World!"), Class::class), + LIST(listOf(1, 2, 3), List::class); + + companion object { + val VALID_CONVERSIONS = + listOf( + FLOAT to DOUBLE, + FLOAT to INTEGER, + FLOAT to LONG, + DOUBLE to FLOAT, + DOUBLE to INTEGER, + DOUBLE to LONG, + INTEGER to FLOAT, + INTEGER to DOUBLE, + INTEGER to LONG, + LONG to FLOAT, + LONG to DOUBLE, + LONG to INTEGER, + CLASS to MAP, + // These aren't actually valid, but coercion configs don't work for String until + // v2.14.0: https://github.com/FasterXML/jackson-databind/issues/3240 + // We currently test on v2.13.4. + BOOLEAN to STRING, + FLOAT to STRING, + DOUBLE to STRING, + INTEGER to STRING, + LONG to STRING, + ) + } + } + + @CartesianTest + fun read(@CartesianTest.Enum shape1: ShapeTestCase, @CartesianTest.Enum shape2: ShapeTestCase) { + val jsonMapper = jsonMapper() + val json = jsonMapper.writeValueAsString(shape1.value) + + val e = catchThrowable { jsonMapper.readValue(json, shape2.kClass.java) } + + if (shape1 == shape2 || shape1 to shape2 in ShapeTestCase.VALID_CONVERSIONS) { + assertThat(e).isNull() + } else { + assertThat(e).isInstanceOf(MismatchedInputException::class.java) + } + } + + enum class LenientLocalDateTimeTestCase(val string: String) { + DATE("1998-04-21"), + DATE_TIME("1998-04-21T04:00:00"), + ZONED_DATE_TIME_1("1998-04-21T04:00:00+03:00"), + ZONED_DATE_TIME_2("1998-04-21T04:00:00Z"), + } + + @ParameterizedTest + @EnumSource + fun readLocalDateTime_lenient(testCase: LenientLocalDateTimeTestCase) { + val jsonMapper = jsonMapper() + val json = jsonMapper.writeValueAsString(testCase.string) + + assertDoesNotThrow { jsonMapper().readValue(json) } + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/core/http/SerializerTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/core/http/SerializerTest.kt deleted file mode 100644 index 159fc882..00000000 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/core/http/SerializerTest.kt +++ /dev/null @@ -1,99 +0,0 @@ -package com.tryfinch.api.core.http - -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.tryfinch.api.core.* -import java.util.* -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -internal class SerializerTest { - @JsonDeserialize(builder = ClassWithBooleanFieldPrefixedWithIs.Builder::class) - @NoAutoDetect - class ClassWithBooleanFieldPrefixedWithIs - private constructor( - private val isActive: JsonField, - private val additionalProperties: Map, - ) { - private var validated: Boolean = false - - private var hashCode: Int = 0 - - fun isActive(): Boolean? = isActive.getNullable("is_active") - - @JsonProperty("is_active") @ExcludeMissing fun _isActive() = isActive - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate() = apply { - if (!validated) { - isActive() - validated = true - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ClassWithBooleanFieldPrefixedWithIs && - isActive == other.isActive && - additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(isActive, additionalProperties) - } - return hashCode - } - - override fun toString() = - "MyClass{isActive=$isActive, additionalProperties=$additionalProperties}" - - companion object { - fun builder() = Builder() - } - - @NoAutoDetect - class Builder internal constructor() { - - private var isActive: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - fun isActive(isActive: Boolean) = isActive(JsonField.of(isActive)) - - @JsonProperty("is_active") - @ExcludeMissing - fun isActive(isActive: JsonField) = apply { this.isActive = isActive } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun build(): ClassWithBooleanFieldPrefixedWithIs = - ClassWithBooleanFieldPrefixedWithIs(isActive, additionalProperties.toImmutable()) - } - } - - @Test - fun serializeBooleanPrefixedWithIs() { - val value = ClassWithBooleanFieldPrefixedWithIs.builder().isActive(true).build() - assertThat(jsonMapper().writeValueAsString(value)).isEqualTo("{\"is_active\":true}") - } -} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccessTokenCreateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccessTokenCreateParamsTest.kt index 3878dc6a..f1b2d6f2 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccessTokenCreateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccessTokenCreateParamsTest.kt @@ -2,11 +2,10 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AccessTokenCreateParamsTest { +internal class AccessTokenCreateParamsTest { @Test fun create() { @@ -30,7 +29,6 @@ class AccessTokenCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.code()).isEqualTo("") assertThat(body.clientId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.clientSecret()).contains("") @@ -43,7 +41,6 @@ class AccessTokenCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.code()).isEqualTo("") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountCreateResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountCreateResponseTest.kt index 77ad0cd6..5e31fef1 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountCreateResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountCreateResponseTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AccountCreateResponseTest { +internal class AccountCreateResponseTest { @Test - fun createAccountCreateResponse() { + fun create() { val accountCreateResponse = AccountCreateResponse.builder() .accessToken("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -19,7 +21,7 @@ class AccountCreateResponseTest { .addProduct("string") .providerId("provider_id") .build() - assertThat(accountCreateResponse).isNotNull + assertThat(accountCreateResponse.accessToken()) .isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(accountCreateResponse.accountId()) @@ -33,4 +35,27 @@ class AccountCreateResponseTest { assertThat(accountCreateResponse.products()).containsExactly("string") assertThat(accountCreateResponse.providerId()).isEqualTo("provider_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val accountCreateResponse = + AccountCreateResponse.builder() + .accessToken("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .accountId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .authenticationType(AccountCreateResponse.AuthenticationType.CREDENTIAL) + .companyId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .connectionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addProduct("string") + .providerId("provider_id") + .build() + + val roundtrippedAccountCreateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(accountCreateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAccountCreateResponse).isEqualTo(accountCreateResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountDisconnectParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountDisconnectParamsTest.kt index 939d87df..346c850b 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountDisconnectParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountDisconnectParamsTest.kt @@ -4,7 +4,7 @@ package com.tryfinch.api.models import org.junit.jupiter.api.Test -class AccountDisconnectParamsTest { +internal class AccountDisconnectParamsTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountIntrospectParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountIntrospectParamsTest.kt index df68f2aa..51ed781b 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountIntrospectParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountIntrospectParamsTest.kt @@ -4,7 +4,7 @@ package com.tryfinch.api.models import org.junit.jupiter.api.Test -class AccountIntrospectParamsTest { +internal class AccountIntrospectParamsTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountUpdateEventTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountUpdateEventTest.kt new file mode 100644 index 00000000..6f34f4e4 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountUpdateEventTest.kt @@ -0,0 +1,2976 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AccountUpdateEventTest { + + @Test + fun create() { + val accountUpdateEvent = + AccountUpdateEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + AccountUpdateEvent.Data.builder() + .authenticationMethod( + AccountUpdateEvent.Data.AuthenticationMethod.builder() + .benefitsSupport( + BenefitsSupport.builder() + .commuter( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .customPostTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .customPreTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .fsaDependentCare( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .fsaMedical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .hsaPost( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .hsaPre( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Dental( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Medical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Vision( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .simple( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .simpleIra( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .build() + ) + .supportedFields( + AccountUpdateEvent.Data.AuthenticationMethod.SupportedFields + .builder() + .company( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .builder() + .id(true) + .accounts( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Accounts + .builder() + .accountName(true) + .accountNumber(true) + .accountType(true) + .institutionName(true) + .routingNumber(true) + .build() + ) + .departments( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Departments + .builder() + .name(true) + .parent( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Departments + .Parent + .builder() + .name(true) + .build() + ) + .build() + ) + .ein(true) + .entity( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Entity + .builder() + .subtype(true) + .type(true) + .build() + ) + .legalName(true) + .locations( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Locations + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .primaryEmail(true) + .primaryPhoneNumber(true) + .build() + ) + .directory( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .builder() + .individuals( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Individuals + .builder() + .id(true) + .department(true) + .firstName(true) + .isActive(true) + .lastName(true) + .manager( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Individuals + .Manager + .builder() + .id(true) + .build() + ) + .middleName(true) + .build() + ) + .paging( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Paging + .builder() + .count(true) + .offset(true) + .build() + ) + .build() + ) + .employment( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .builder() + .id(true) + .classCode(true) + .customFields(true) + .department( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Department + .builder() + .name(true) + .build() + ) + .employment( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Employment + .builder() + .subtype(true) + .type(true) + .build() + ) + .employmentStatus(true) + .endDate(true) + .firstName(true) + .income( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Income + .builder() + .amount(true) + .currency(true) + .unit(true) + .build() + ) + .incomeHistory(true) + .isActive(true) + .lastName(true) + .location( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Location + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .manager( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Manager + .builder() + .id(true) + .build() + ) + .middleName(true) + .startDate(true) + .title(true) + .build() + ) + .individual( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .builder() + .id(true) + .dob(true) + .emails( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .Emails + .builder() + .data(true) + .type(true) + .build() + ) + .encryptedSsn(true) + .ethnicity(true) + .firstName(true) + .gender(true) + .lastName(true) + .middleName(true) + .phoneNumbers( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .PhoneNumbers + .builder() + .data(true) + .type(true) + .build() + ) + .preferredName(true) + .residence( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .Residence + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .ssn(true) + .build() + ) + .payGroup( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayGroupFields + .builder() + .id(true) + .individualIds(true) + .name(true) + .payFrequencies(true) + .build() + ) + .payStatement( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .builder() + .paging( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .Paging + .builder() + .count(true) + .offset(true) + .build() + ) + .payStatements( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .builder() + .earnings( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .Earnings + .builder() + .amount(true) + .currency(true) + .name(true) + .type(true) + .build() + ) + .employeeDeductions( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .EmployeeDeductions + .builder() + .amount(true) + .currency(true) + .name(true) + .preTax(true) + .type(true) + .build() + ) + .employerContributions( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .EmployerContributions + .builder() + .amount(true) + .currency(true) + .name(true) + .build() + ) + .grossPay(true) + .individualId(true) + .netPay(true) + .paymentMethod(true) + .taxes( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .Taxes + .builder() + .amount(true) + .currency(true) + .employer(true) + .name(true) + .type(true) + .build() + ) + .totalHours(true) + .type(true) + .build() + ) + .build() + ) + .payment( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPaymentFields + .builder() + .id(true) + .companyDebit(true) + .debitDate(true) + .employeeTaxes(true) + .employerTaxes(true) + .grossPay(true) + .individualIds(true) + .netPay(true) + .payDate(true) + .payFrequencies(true) + .payGroupIds(true) + .payPeriod( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPaymentFields + .PayPeriod + .builder() + .endDate(true) + .startDate(true) + .build() + ) + .build() + ) + .build() + ) + .type(AccountUpdateEvent.Data.AuthenticationMethod.Type.ASSISTED) + .build() + ) + .status(ConnectionStatusType.PENDING) + .build() + ) + .eventType(AccountUpdateEvent.EventType.ACCOUNT_UPDATED) + .build() + + assertThat(accountUpdateEvent.accountId()).isEqualTo("account_id") + assertThat(accountUpdateEvent.companyId()).isEqualTo("company_id") + assertThat(accountUpdateEvent.connectionId()).contains("connection_id") + assertThat(accountUpdateEvent.data()) + .contains( + AccountUpdateEvent.Data.builder() + .authenticationMethod( + AccountUpdateEvent.Data.AuthenticationMethod.builder() + .benefitsSupport( + BenefitsSupport.builder() + .commuter( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .customPostTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .customPreTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .fsaDependentCare( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .fsaMedical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .hsaPost( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .hsaPre( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Dental( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Medical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Vision( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .simple( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .simpleIra( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .build() + ) + .supportedFields( + AccountUpdateEvent.Data.AuthenticationMethod.SupportedFields + .builder() + .company( + AccountUpdateEvent.Data.AuthenticationMethod.SupportedFields + .SupportedCompanyFields + .builder() + .id(true) + .accounts( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Accounts + .builder() + .accountName(true) + .accountNumber(true) + .accountType(true) + .institutionName(true) + .routingNumber(true) + .build() + ) + .departments( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Departments + .builder() + .name(true) + .parent( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Departments + .Parent + .builder() + .name(true) + .build() + ) + .build() + ) + .ein(true) + .entity( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Entity + .builder() + .subtype(true) + .type(true) + .build() + ) + .legalName(true) + .locations( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Locations + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .primaryEmail(true) + .primaryPhoneNumber(true) + .build() + ) + .directory( + AccountUpdateEvent.Data.AuthenticationMethod.SupportedFields + .SupportedDirectoryFields + .builder() + .individuals( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Individuals + .builder() + .id(true) + .department(true) + .firstName(true) + .isActive(true) + .lastName(true) + .manager( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Individuals + .Manager + .builder() + .id(true) + .build() + ) + .middleName(true) + .build() + ) + .paging( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Paging + .builder() + .count(true) + .offset(true) + .build() + ) + .build() + ) + .employment( + AccountUpdateEvent.Data.AuthenticationMethod.SupportedFields + .SupportedEmploymentFields + .builder() + .id(true) + .classCode(true) + .customFields(true) + .department( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Department + .builder() + .name(true) + .build() + ) + .employment( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Employment + .builder() + .subtype(true) + .type(true) + .build() + ) + .employmentStatus(true) + .endDate(true) + .firstName(true) + .income( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Income + .builder() + .amount(true) + .currency(true) + .unit(true) + .build() + ) + .incomeHistory(true) + .isActive(true) + .lastName(true) + .location( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Location + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .manager( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Manager + .builder() + .id(true) + .build() + ) + .middleName(true) + .startDate(true) + .title(true) + .build() + ) + .individual( + AccountUpdateEvent.Data.AuthenticationMethod.SupportedFields + .SupportedIndividualFields + .builder() + .id(true) + .dob(true) + .emails( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .Emails + .builder() + .data(true) + .type(true) + .build() + ) + .encryptedSsn(true) + .ethnicity(true) + .firstName(true) + .gender(true) + .lastName(true) + .middleName(true) + .phoneNumbers( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .PhoneNumbers + .builder() + .data(true) + .type(true) + .build() + ) + .preferredName(true) + .residence( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .Residence + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .ssn(true) + .build() + ) + .payGroup( + AccountUpdateEvent.Data.AuthenticationMethod.SupportedFields + .SupportedPayGroupFields + .builder() + .id(true) + .individualIds(true) + .name(true) + .payFrequencies(true) + .build() + ) + .payStatement( + AccountUpdateEvent.Data.AuthenticationMethod.SupportedFields + .SupportedPayStatementFields + .builder() + .paging( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .Paging + .builder() + .count(true) + .offset(true) + .build() + ) + .payStatements( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .builder() + .earnings( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .Earnings + .builder() + .amount(true) + .currency(true) + .name(true) + .type(true) + .build() + ) + .employeeDeductions( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .EmployeeDeductions + .builder() + .amount(true) + .currency(true) + .name(true) + .preTax(true) + .type(true) + .build() + ) + .employerContributions( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .EmployerContributions + .builder() + .amount(true) + .currency(true) + .name(true) + .build() + ) + .grossPay(true) + .individualId(true) + .netPay(true) + .paymentMethod(true) + .taxes( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .Taxes + .builder() + .amount(true) + .currency(true) + .employer(true) + .name(true) + .type(true) + .build() + ) + .totalHours(true) + .type(true) + .build() + ) + .build() + ) + .payment( + AccountUpdateEvent.Data.AuthenticationMethod.SupportedFields + .SupportedPaymentFields + .builder() + .id(true) + .companyDebit(true) + .debitDate(true) + .employeeTaxes(true) + .employerTaxes(true) + .grossPay(true) + .individualIds(true) + .netPay(true) + .payDate(true) + .payFrequencies(true) + .payGroupIds(true) + .payPeriod( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPaymentFields + .PayPeriod + .builder() + .endDate(true) + .startDate(true) + .build() + ) + .build() + ) + .build() + ) + .type(AccountUpdateEvent.Data.AuthenticationMethod.Type.ASSISTED) + .build() + ) + .status(ConnectionStatusType.PENDING) + .build() + ) + assertThat(accountUpdateEvent.eventType()) + .contains(AccountUpdateEvent.EventType.ACCOUNT_UPDATED) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val accountUpdateEvent = + AccountUpdateEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + AccountUpdateEvent.Data.builder() + .authenticationMethod( + AccountUpdateEvent.Data.AuthenticationMethod.builder() + .benefitsSupport( + BenefitsSupport.builder() + .commuter( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .customPostTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .customPreTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .fsaDependentCare( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .fsaMedical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .hsaPost( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .hsaPre( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Dental( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Medical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Vision( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .simple( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .simpleIra( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .build() + ) + .supportedFields( + AccountUpdateEvent.Data.AuthenticationMethod.SupportedFields + .builder() + .company( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .builder() + .id(true) + .accounts( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Accounts + .builder() + .accountName(true) + .accountNumber(true) + .accountType(true) + .institutionName(true) + .routingNumber(true) + .build() + ) + .departments( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Departments + .builder() + .name(true) + .parent( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Departments + .Parent + .builder() + .name(true) + .build() + ) + .build() + ) + .ein(true) + .entity( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Entity + .builder() + .subtype(true) + .type(true) + .build() + ) + .legalName(true) + .locations( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Locations + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .primaryEmail(true) + .primaryPhoneNumber(true) + .build() + ) + .directory( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .builder() + .individuals( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Individuals + .builder() + .id(true) + .department(true) + .firstName(true) + .isActive(true) + .lastName(true) + .manager( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Individuals + .Manager + .builder() + .id(true) + .build() + ) + .middleName(true) + .build() + ) + .paging( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Paging + .builder() + .count(true) + .offset(true) + .build() + ) + .build() + ) + .employment( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .builder() + .id(true) + .classCode(true) + .customFields(true) + .department( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Department + .builder() + .name(true) + .build() + ) + .employment( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Employment + .builder() + .subtype(true) + .type(true) + .build() + ) + .employmentStatus(true) + .endDate(true) + .firstName(true) + .income( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Income + .builder() + .amount(true) + .currency(true) + .unit(true) + .build() + ) + .incomeHistory(true) + .isActive(true) + .lastName(true) + .location( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Location + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .manager( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Manager + .builder() + .id(true) + .build() + ) + .middleName(true) + .startDate(true) + .title(true) + .build() + ) + .individual( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .builder() + .id(true) + .dob(true) + .emails( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .Emails + .builder() + .data(true) + .type(true) + .build() + ) + .encryptedSsn(true) + .ethnicity(true) + .firstName(true) + .gender(true) + .lastName(true) + .middleName(true) + .phoneNumbers( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .PhoneNumbers + .builder() + .data(true) + .type(true) + .build() + ) + .preferredName(true) + .residence( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .Residence + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .ssn(true) + .build() + ) + .payGroup( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayGroupFields + .builder() + .id(true) + .individualIds(true) + .name(true) + .payFrequencies(true) + .build() + ) + .payStatement( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .builder() + .paging( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .Paging + .builder() + .count(true) + .offset(true) + .build() + ) + .payStatements( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .builder() + .earnings( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .Earnings + .builder() + .amount(true) + .currency(true) + .name(true) + .type(true) + .build() + ) + .employeeDeductions( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .EmployeeDeductions + .builder() + .amount(true) + .currency(true) + .name(true) + .preTax(true) + .type(true) + .build() + ) + .employerContributions( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .EmployerContributions + .builder() + .amount(true) + .currency(true) + .name(true) + .build() + ) + .grossPay(true) + .individualId(true) + .netPay(true) + .paymentMethod(true) + .taxes( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .Taxes + .builder() + .amount(true) + .currency(true) + .employer(true) + .name(true) + .type(true) + .build() + ) + .totalHours(true) + .type(true) + .build() + ) + .build() + ) + .payment( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPaymentFields + .builder() + .id(true) + .companyDebit(true) + .debitDate(true) + .employeeTaxes(true) + .employerTaxes(true) + .grossPay(true) + .individualIds(true) + .netPay(true) + .payDate(true) + .payFrequencies(true) + .payGroupIds(true) + .payPeriod( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPaymentFields + .PayPeriod + .builder() + .endDate(true) + .startDate(true) + .build() + ) + .build() + ) + .build() + ) + .type(AccountUpdateEvent.Data.AuthenticationMethod.Type.ASSISTED) + .build() + ) + .status(ConnectionStatusType.PENDING) + .build() + ) + .eventType(AccountUpdateEvent.EventType.ACCOUNT_UPDATED) + .build() + + val roundtrippedAccountUpdateEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(accountUpdateEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAccountUpdateEvent).isEqualTo(accountUpdateEvent) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountUpdateResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountUpdateResponseTest.kt index 822eb797..20af0d97 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountUpdateResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AccountUpdateResponseTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AccountUpdateResponseTest { +internal class AccountUpdateResponseTest { @Test - fun createAccountUpdateResponse() { + fun create() { val accountUpdateResponse = AccountUpdateResponse.builder() .accountId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -18,7 +20,7 @@ class AccountUpdateResponseTest { .providerId("provider_id") .connectionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(accountUpdateResponse).isNotNull + assertThat(accountUpdateResponse.accountId()) .isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(accountUpdateResponse.authenticationType()) @@ -30,4 +32,26 @@ class AccountUpdateResponseTest { assertThat(accountUpdateResponse.connectionId()) .contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val accountUpdateResponse = + AccountUpdateResponse.builder() + .accountId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .authenticationType(AccountUpdateResponse.AuthenticationType.CREDENTIAL) + .companyId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addProduct("string") + .providerId("provider_id") + .connectionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedAccountUpdateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(accountUpdateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAccountUpdateResponse).isEqualTo(accountUpdateResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AutomatedAsyncJobTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AutomatedAsyncJobTest.kt index 4b581077..14fbbfeb 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AutomatedAsyncJobTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AutomatedAsyncJobTest.kt @@ -2,14 +2,16 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AutomatedAsyncJobTest { +internal class AutomatedAsyncJobTest { @Test - fun createAutomatedAsyncJob() { + fun create() { val automatedAsyncJob = AutomatedAsyncJob.builder() .completedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) @@ -22,7 +24,7 @@ class AutomatedAsyncJobTest { .status(AutomatedAsyncJob.Status.PENDING) .type(AutomatedAsyncJob.Type.DATA_SYNC_ALL) .build() - assertThat(automatedAsyncJob).isNotNull + assertThat(automatedAsyncJob.completedAt()) .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) assertThat(automatedAsyncJob.createdAt()) @@ -38,4 +40,29 @@ class AutomatedAsyncJobTest { assertThat(automatedAsyncJob.status()).isEqualTo(AutomatedAsyncJob.Status.PENDING) assertThat(automatedAsyncJob.type()).isEqualTo(AutomatedAsyncJob.Type.DATA_SYNC_ALL) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val automatedAsyncJob = + AutomatedAsyncJob.builder() + .completedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .jobId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .jobUrl("job_url") + .params(AutomatedAsyncJob.Params.builder().individualId("individual_id").build()) + .scheduledAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .startedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .status(AutomatedAsyncJob.Status.PENDING) + .type(AutomatedAsyncJob.Type.DATA_SYNC_ALL) + .build() + + val roundtrippedAutomatedAsyncJob = + jsonMapper.readValue( + jsonMapper.writeValueAsString(automatedAsyncJob), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAutomatedAsyncJob).isEqualTo(automatedAsyncJob) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AutomatedCreateResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AutomatedCreateResponseTest.kt index 9fad95d7..28a4fc41 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AutomatedCreateResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AutomatedCreateResponseTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class AutomatedCreateResponseTest { +internal class AutomatedCreateResponseTest { @Test - fun createAutomatedCreateResponse() { + fun create() { val automatedCreateResponse = AutomatedCreateResponse.builder() .allowedRefreshes(0L) @@ -16,11 +18,31 @@ class AutomatedCreateResponseTest { .jobUrl("job_url") .remainingRefreshes(0L) .build() - assertThat(automatedCreateResponse).isNotNull + assertThat(automatedCreateResponse.allowedRefreshes()).isEqualTo(0L) assertThat(automatedCreateResponse.jobId()) .isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(automatedCreateResponse.jobUrl()).isEqualTo("job_url") assertThat(automatedCreateResponse.remainingRefreshes()).isEqualTo(0L) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val automatedCreateResponse = + AutomatedCreateResponse.builder() + .allowedRefreshes(0L) + .jobId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .jobUrl("job_url") + .remainingRefreshes(0L) + .build() + + val roundtrippedAutomatedCreateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(automatedCreateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAutomatedCreateResponse).isEqualTo(automatedCreateResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AutomatedListResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AutomatedListResponseTest.kt new file mode 100644 index 00000000..81a732eb --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/AutomatedListResponseTest.kt @@ -0,0 +1,125 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AutomatedListResponseTest { + + @Test + fun create() { + val automatedListResponse = + AutomatedListResponse.builder() + .addData( + AutomatedAsyncJob.builder() + .completedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .jobId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .jobUrl("job_url") + .params( + AutomatedAsyncJob.Params.builder().individualId("individual_id").build() + ) + .scheduledAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .startedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .status(AutomatedAsyncJob.Status.PENDING) + .type(AutomatedAsyncJob.Type.DATA_SYNC_ALL) + .build() + ) + .meta( + AutomatedListResponse.Meta.builder() + .quotas( + AutomatedListResponse.Meta.Quotas.builder() + .dataSyncAll( + AutomatedListResponse.Meta.Quotas.DataSyncAll.builder() + .allowedRefreshes(0L) + .remainingRefreshes(0L) + .build() + ) + .build() + ) + .build() + ) + .build() + + assertThat(automatedListResponse.data()) + .containsExactly( + AutomatedAsyncJob.builder() + .completedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .jobId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .jobUrl("job_url") + .params( + AutomatedAsyncJob.Params.builder().individualId("individual_id").build() + ) + .scheduledAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .startedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .status(AutomatedAsyncJob.Status.PENDING) + .type(AutomatedAsyncJob.Type.DATA_SYNC_ALL) + .build() + ) + assertThat(automatedListResponse.meta()) + .isEqualTo( + AutomatedListResponse.Meta.builder() + .quotas( + AutomatedListResponse.Meta.Quotas.builder() + .dataSyncAll( + AutomatedListResponse.Meta.Quotas.DataSyncAll.builder() + .allowedRefreshes(0L) + .remainingRefreshes(0L) + .build() + ) + .build() + ) + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val automatedListResponse = + AutomatedListResponse.builder() + .addData( + AutomatedAsyncJob.builder() + .completedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .jobId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .jobUrl("job_url") + .params( + AutomatedAsyncJob.Params.builder().individualId("individual_id").build() + ) + .scheduledAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .startedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .status(AutomatedAsyncJob.Status.PENDING) + .type(AutomatedAsyncJob.Type.DATA_SYNC_ALL) + .build() + ) + .meta( + AutomatedListResponse.Meta.builder() + .quotas( + AutomatedListResponse.Meta.Quotas.builder() + .dataSyncAll( + AutomatedListResponse.Meta.Quotas.DataSyncAll.builder() + .allowedRefreshes(0L) + .remainingRefreshes(0L) + .build() + ) + .build() + ) + .build() + ) + .build() + + val roundtrippedAutomatedListResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(automatedListResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAutomatedListResponse).isEqualTo(automatedListResponse) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BaseWebhookEventTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BaseWebhookEventTest.kt index 85809beb..1c0999b9 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BaseWebhookEventTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BaseWebhookEventTest.kt @@ -2,22 +2,43 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class BaseWebhookEventTest { +internal class BaseWebhookEventTest { @Test - fun createBaseWebhookEvent() { + fun create() { val baseWebhookEvent = BaseWebhookEvent.builder() .accountId("account_id") .companyId("company_id") .connectionId("connection_id") .build() - assertThat(baseWebhookEvent).isNotNull + assertThat(baseWebhookEvent.accountId()).isEqualTo("account_id") assertThat(baseWebhookEvent.companyId()).isEqualTo("company_id") assertThat(baseWebhookEvent.connectionId()).contains("connection_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val baseWebhookEvent = + BaseWebhookEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .build() + + val roundtrippedBaseWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(baseWebhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedBaseWebhookEvent).isEqualTo(baseWebhookEvent) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BenefitContributionTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BenefitContributionTest.kt index 08448c53..7ffc1e7e 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BenefitContributionTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BenefitContributionTest.kt @@ -2,17 +2,34 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class BenefitContributionTest { +internal class BenefitContributionTest { @Test - fun createBenefitContribution() { + fun create() { val benefitContribution = BenefitContribution.builder().amount(0L).type(BenefitContribution.Type.FIXED).build() - assertThat(benefitContribution).isNotNull + assertThat(benefitContribution.amount()).contains(0L) assertThat(benefitContribution.type()).contains(BenefitContribution.Type.FIXED) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val benefitContribution = + BenefitContribution.builder().amount(0L).type(BenefitContribution.Type.FIXED).build() + + val roundtrippedBenefitContribution = + jsonMapper.readValue( + jsonMapper.writeValueAsString(benefitContribution), + jacksonTypeRef(), + ) + + assertThat(roundtrippedBenefitContribution).isEqualTo(benefitContribution) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BenefitFeaturesAndOperationsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BenefitFeaturesAndOperationsTest.kt index c9ceed88..8849aba2 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BenefitFeaturesAndOperationsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BenefitFeaturesAndOperationsTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class BenefitFeaturesAndOperationsTest { +internal class BenefitFeaturesAndOperationsTest { @Test - fun createBenefitFeaturesAndOperations() { + fun create() { val benefitFeaturesAndOperations = BenefitFeaturesAndOperations.builder() .supportedFeatures( @@ -50,7 +52,7 @@ class BenefitFeaturesAndOperationsTest { .build() ) .build() - assertThat(benefitFeaturesAndOperations).isNotNull + assertThat(benefitFeaturesAndOperations.supportedFeatures()) .contains( BenefitFeaturesAndOperations.BenefitFeature.builder() @@ -91,4 +93,58 @@ class BenefitFeaturesAndOperationsTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val benefitFeaturesAndOperations = + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature.CompanyContribution.FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature.EmployeeDeduction.FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature.HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + + val roundtrippedBenefitFeaturesAndOperations = + jsonMapper.readValue( + jsonMapper.writeValueAsString(benefitFeaturesAndOperations), + jacksonTypeRef(), + ) + + assertThat(roundtrippedBenefitFeaturesAndOperations).isEqualTo(benefitFeaturesAndOperations) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BenefitsSupportTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BenefitsSupportTest.kt index 1d3cc3cb..6490d096 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BenefitsSupportTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/BenefitsSupportTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class BenefitsSupportTest { +internal class BenefitsSupportTest { @Test - fun createBenefitsSupport() { + fun create() { val benefitsSupport = BenefitsSupport.builder() .commuter( @@ -540,7 +542,7 @@ class BenefitsSupportTest { .build() ) .build() - assertThat(benefitsSupport).isNotNull + assertThat(benefitsSupport.commuter()) .contains( BenefitFeaturesAndOperations.builder() @@ -1070,4 +1072,548 @@ class BenefitsSupportTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val benefitsSupport = + BenefitsSupport.builder() + .commuter( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature.CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature.EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature.HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .customPostTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature.CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature.EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature.HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .customPreTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature.CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature.EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature.HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .fsaDependentCare( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature.CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature.EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature.HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .fsaMedical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature.CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature.EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature.HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .hsaPost( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature.CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature.EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature.HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .hsaPre( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature.CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature.EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature.HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Dental( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature.CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature.EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature.HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Medical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature.CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature.EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature.HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Vision( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature.CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature.EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature.HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .simple( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature.CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature.EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature.HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .simpleIra( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature.CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature.EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature.HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .build() + + val roundtrippedBenefitsSupport = + jsonMapper.readValue( + jsonMapper.writeValueAsString(benefitsSupport), + jacksonTypeRef(), + ) + + assertThat(roundtrippedBenefitsSupport).isEqualTo(benefitsSupport) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyBenefitTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyBenefitTest.kt index e3f8d682..b4ec445b 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyBenefitTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyBenefitTest.kt @@ -2,24 +2,46 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class CompanyBenefitTest { +internal class CompanyBenefitTest { @Test - fun createCompanyBenefit() { + fun create() { val companyBenefit = CompanyBenefit.builder() - .benefitId("benefit_id") + .benefitId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .description("description") .frequency(BenefitFrequency.ONE_TIME) .type(BenefitType._401K) .build() - assertThat(companyBenefit).isNotNull - assertThat(companyBenefit.benefitId()).isEqualTo("benefit_id") + + assertThat(companyBenefit.benefitId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(companyBenefit.description()).contains("description") assertThat(companyBenefit.frequency()).contains(BenefitFrequency.ONE_TIME) assertThat(companyBenefit.type()).contains(BenefitType._401K) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val companyBenefit = + CompanyBenefit.builder() + .benefitId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .frequency(BenefitFrequency.ONE_TIME) + .type(BenefitType._401K) + .build() + + val roundtrippedCompanyBenefit = + jsonMapper.readValue( + jsonMapper.writeValueAsString(companyBenefit), + jacksonTypeRef(), + ) + + assertThat(roundtrippedCompanyBenefit).isEqualTo(companyBenefit) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyEventTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyEventTest.kt new file mode 100644 index 00000000..91f000b6 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyEventTest.kt @@ -0,0 +1,64 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class CompanyEventTest { + + @Test + fun create() { + val companyEvent = + CompanyEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + CompanyEvent.Data.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .eventType(CompanyEvent.EventType.COMPANY_UPDATED) + .build() + + assertThat(companyEvent.accountId()).isEqualTo("account_id") + assertThat(companyEvent.companyId()).isEqualTo("company_id") + assertThat(companyEvent.connectionId()).contains("connection_id") + assertThat(companyEvent.data()) + .contains( + CompanyEvent.Data.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(companyEvent.eventType()).contains(CompanyEvent.EventType.COMPANY_UPDATED) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val companyEvent = + CompanyEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + CompanyEvent.Data.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .eventType(CompanyEvent.EventType.COMPANY_UPDATED) + .build() + + val roundtrippedCompanyEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(companyEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedCompanyEvent).isEqualTo(companyEvent) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyTest.kt index 4ca6ddb3..ec22941d 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyTest.kt @@ -2,16 +2,19 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class CompanyTest { +internal class CompanyTest { @Test - fun createCompany() { + fun create() { val company = Company.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .addAccount( Company.Account.builder() .accountName("account_name") @@ -47,12 +50,12 @@ class CompanyTest { .state("state") .build() ) - .primaryEmail("primary_email") + .primaryEmail("dev@stainless.com") .primaryPhoneNumber("primary_phone_number") .build() - assertThat(company).isNotNull - assertThat(company.id()).isEqualTo("id") - assertThat(company.accounts().get()) + + assertThat(company.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(company.accounts().getOrNull()) .containsExactly( Company.Account.builder() .accountName("account_name") @@ -62,7 +65,7 @@ class CompanyTest { .routingNumber("routing_number") .build() ) - assertThat(company.departments().get()) + assertThat(company.departments().getOrNull()) .containsExactly( Company.Department.builder() .name("name") @@ -78,7 +81,7 @@ class CompanyTest { .build() ) assertThat(company.legalName()).contains("legal_name") - assertThat(company.locations().get()) + assertThat(company.locations().getOrNull()) .containsExactly( Location.builder() .city("city") @@ -91,7 +94,58 @@ class CompanyTest { .state("state") .build() ) - assertThat(company.primaryEmail()).contains("primary_email") + assertThat(company.primaryEmail()).contains("dev@stainless.com") assertThat(company.primaryPhoneNumber()).contains("primary_phone_number") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val company = + Company.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addAccount( + Company.Account.builder() + .accountName("account_name") + .accountNumber("account_number") + .accountType(Company.Account.AccountType.CHECKING) + .institutionName("institution_name") + .routingNumber("routing_number") + .build() + ) + .addDepartment( + Company.Department.builder() + .name("name") + .parent(Company.Department.Parent.builder().name("name").build()) + .build() + ) + .ein("ein") + .entity( + Company.Entity.builder() + .subtype(Company.Entity.Subtype.S_CORPORATION) + .type(Company.Entity.Type.LLC) + .build() + ) + .legalName("legal_name") + .addLocation( + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() + ) + .primaryEmail("dev@stainless.com") + .primaryPhoneNumber("primary_phone_number") + .build() + + val roundtrippedCompany = + jsonMapper.readValue(jsonMapper.writeValueAsString(company), jacksonTypeRef()) + + assertThat(roundtrippedCompany).isEqualTo(company) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyUpdateResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyUpdateResponseTest.kt index c08e1171..40d8cb6b 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyUpdateResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CompanyUpdateResponseTest.kt @@ -2,13 +2,16 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class CompanyUpdateResponseTest { +internal class CompanyUpdateResponseTest { @Test - fun createCompanyUpdateResponse() { + fun create() { val companyUpdateResponse = CompanyUpdateResponse.builder() .addAccount( @@ -48,11 +51,11 @@ class CompanyUpdateResponseTest { .state("state") .build() ) - .primaryEmail("primary_email") + .primaryEmail("dev@stainless.com") .primaryPhoneNumber("primary_phone_number") .build() - assertThat(companyUpdateResponse).isNotNull - assertThat(companyUpdateResponse.accounts().get()) + + assertThat(companyUpdateResponse.accounts().getOrNull()) .containsExactly( CompanyUpdateResponse.Account.builder() .accountName("account_name") @@ -62,7 +65,7 @@ class CompanyUpdateResponseTest { .routingNumber("routing_number") .build() ) - assertThat(companyUpdateResponse.departments().get()) + assertThat(companyUpdateResponse.departments().getOrNull()) .containsExactly( CompanyUpdateResponse.Department.builder() .name("name") @@ -78,7 +81,7 @@ class CompanyUpdateResponseTest { .build() ) assertThat(companyUpdateResponse.legalName()).contains("legal_name") - assertThat(companyUpdateResponse.locations().get()) + assertThat(companyUpdateResponse.locations().getOrNull()) .containsExactly( Location.builder() .city("city") @@ -91,7 +94,62 @@ class CompanyUpdateResponseTest { .state("state") .build() ) - assertThat(companyUpdateResponse.primaryEmail()).contains("primary_email") + assertThat(companyUpdateResponse.primaryEmail()).contains("dev@stainless.com") assertThat(companyUpdateResponse.primaryPhoneNumber()).contains("primary_phone_number") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val companyUpdateResponse = + CompanyUpdateResponse.builder() + .addAccount( + CompanyUpdateResponse.Account.builder() + .accountName("account_name") + .accountNumber("account_number") + .accountType(CompanyUpdateResponse.Account.AccountType.CHECKING) + .institutionName("institution_name") + .routingNumber("routing_number") + .build() + ) + .addDepartment( + CompanyUpdateResponse.Department.builder() + .name("name") + .parent( + CompanyUpdateResponse.Department.Parent.builder().name("name").build() + ) + .build() + ) + .ein("ein") + .entity( + CompanyUpdateResponse.Entity.builder() + .subtype(CompanyUpdateResponse.Entity.Subtype.S_CORPORATION) + .type(CompanyUpdateResponse.Entity.Type.LLC) + .build() + ) + .legalName("legal_name") + .addLocation( + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() + ) + .primaryEmail("dev@stainless.com") + .primaryPhoneNumber("primary_phone_number") + .build() + + val roundtrippedCompanyUpdateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(companyUpdateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedCompanyUpdateResponse).isEqualTo(companyUpdateResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ConnectSessionNewParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ConnectSessionNewParamsTest.kt index ee91137d..548a1249 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ConnectSessionNewParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ConnectSessionNewParamsTest.kt @@ -2,11 +2,10 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ConnectSessionNewParamsTest { +internal class ConnectSessionNewParamsTest { @Test fun create() { @@ -14,7 +13,7 @@ class ConnectSessionNewParamsTest { .customerId("x") .customerName("x") .addProduct(ConnectSessionNewParams.ConnectProducts.COMPANY) - .customerEmail("dev@stainlessapi.com") + .customerEmail("dev@stainless.com") .integration( ConnectSessionNewParams.Integration.builder() .authMethod(ConnectSessionNewParams.Integration.AuthMethod.ASSISTED) @@ -35,7 +34,7 @@ class ConnectSessionNewParamsTest { .customerId("x") .customerName("x") .addProduct(ConnectSessionNewParams.ConnectProducts.COMPANY) - .customerEmail("dev@stainlessapi.com") + .customerEmail("dev@stainless.com") .integration( ConnectSessionNewParams.Integration.builder() .authMethod(ConnectSessionNewParams.Integration.AuthMethod.ASSISTED) @@ -50,12 +49,10 @@ class ConnectSessionNewParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.customerId()).isEqualTo("x") assertThat(body.customerName()).isEqualTo("x") - assertThat(body.products()) - .isEqualTo(listOf(ConnectSessionNewParams.ConnectProducts.COMPANY)) - assertThat(body.customerEmail()).contains("dev@stainlessapi.com") + assertThat(body.products()).containsExactly(ConnectSessionNewParams.ConnectProducts.COMPANY) + assertThat(body.customerEmail()).contains("dev@stainless.com") assertThat(body.integration()) .contains( ConnectSessionNewParams.Integration.builder() @@ -80,10 +77,8 @@ class ConnectSessionNewParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.customerId()).isEqualTo("x") assertThat(body.customerName()).isEqualTo("x") - assertThat(body.products()) - .isEqualTo(listOf(ConnectSessionNewParams.ConnectProducts.COMPANY)) + assertThat(body.products()).containsExactly(ConnectSessionNewParams.ConnectProducts.COMPANY) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ConnectSessionReauthenticateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ConnectSessionReauthenticateParamsTest.kt index bd7bdfdc..f4604548 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ConnectSessionReauthenticateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ConnectSessionReauthenticateParamsTest.kt @@ -2,11 +2,11 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ConnectSessionReauthenticateParamsTest { +internal class ConnectSessionReauthenticateParamsTest { @Test fun create() { @@ -30,11 +30,10 @@ class ConnectSessionReauthenticateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.connectionId()).isEqualTo("connection_id") assertThat(body.minutesToExpire()).contains(0L) - assertThat(body.products()) - .contains(listOf(ConnectSessionReauthenticateParams.ConnectProducts.COMPANY)) + assertThat(body.products().getOrNull()) + .containsExactly(ConnectSessionReauthenticateParams.ConnectProducts.COMPANY) assertThat(body.redirectUri()).contains("https://example.com") } @@ -45,7 +44,6 @@ class ConnectSessionReauthenticateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.connectionId()).isEqualTo("connection_id") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ConnectionCreateResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ConnectionCreateResponseTest.kt index 742816d8..1a3b4808 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ConnectionCreateResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ConnectionCreateResponseTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ConnectionCreateResponseTest { +internal class ConnectionCreateResponseTest { @Test - fun createConnectionCreateResponse() { + fun create() { val connectionCreateResponse = ConnectionCreateResponse.builder() .accessToken("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -20,7 +22,7 @@ class ConnectionCreateResponseTest { .providerId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .tokenType("token_type") .build() - assertThat(connectionCreateResponse).isNotNull + assertThat(connectionCreateResponse.accessToken()) .isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(connectionCreateResponse.accountId()) @@ -36,4 +38,28 @@ class ConnectionCreateResponseTest { .isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(connectionCreateResponse.tokenType()).contains("token_type") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val connectionCreateResponse = + ConnectionCreateResponse.builder() + .accessToken("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .accountId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .authenticationType(ConnectionCreateResponse.AuthenticationType.CREDENTIAL) + .companyId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .connectionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addProduct("string") + .providerId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .tokenType("token_type") + .build() + + val roundtrippedConnectionCreateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(connectionCreateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedConnectionCreateResponse).isEqualTo(connectionCreateResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CreateAccessTokenResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CreateAccessTokenResponseTest.kt index 86c7535f..70c06a3b 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CreateAccessTokenResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CreateAccessTokenResponseTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class CreateAccessTokenResponseTest { +internal class CreateAccessTokenResponseTest { @Test - fun createCreateAccessTokenResponse() { + fun create() { val createAccessTokenResponse = CreateAccessTokenResponse.builder() .accessToken("access_token") @@ -22,7 +24,7 @@ class CreateAccessTokenResponseTest { .customerId("customer_id") .tokenType("token_type") .build() - assertThat(createAccessTokenResponse).isNotNull + assertThat(createAccessTokenResponse.accessToken()).isEqualTo("access_token") assertThat(createAccessTokenResponse.accountId()).isEqualTo("account_id") assertThat(createAccessTokenResponse.clientType()) @@ -36,4 +38,30 @@ class CreateAccessTokenResponseTest { assertThat(createAccessTokenResponse.customerId()).contains("customer_id") assertThat(createAccessTokenResponse.tokenType()).contains("token_type") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val createAccessTokenResponse = + CreateAccessTokenResponse.builder() + .accessToken("access_token") + .accountId("account_id") + .clientType(CreateAccessTokenResponse.ClientType.PRODUCTION) + .companyId("company_id") + .connectionId("connection_id") + .connectionType(CreateAccessTokenResponse.ConnectionType.PROVIDER) + .addProduct("string") + .providerId("provider_id") + .customerId("customer_id") + .tokenType("token_type") + .build() + + val roundtrippedCreateAccessTokenResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(createAccessTokenResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedCreateAccessTokenResponse).isEqualTo(createAccessTokenResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CreateCompanyBenefitsResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CreateCompanyBenefitsResponseTest.kt index 1edef034..ea9b034c 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CreateCompanyBenefitsResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/CreateCompanyBenefitsResponseTest.kt @@ -2,16 +2,39 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class CreateCompanyBenefitsResponseTest { +internal class CreateCompanyBenefitsResponseTest { @Test - fun createCreateCompanyBenefitsResponse() { + fun create() { val createCompanyBenefitsResponse = - CreateCompanyBenefitsResponse.builder().benefitId("benefit_id").build() - assertThat(createCompanyBenefitsResponse).isNotNull - assertThat(createCompanyBenefitsResponse.benefitId()).isEqualTo("benefit_id") + CreateCompanyBenefitsResponse.builder() + .benefitId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(createCompanyBenefitsResponse.benefitId()) + .isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val createCompanyBenefitsResponse = + CreateCompanyBenefitsResponse.builder() + .benefitId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedCreateCompanyBenefitsResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(createCompanyBenefitsResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedCreateCompanyBenefitsResponse) + .isEqualTo(createCompanyBenefitsResponse) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DirectoryCreateResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DirectoryCreateResponseTest.kt new file mode 100644 index 00000000..5fb1523b --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DirectoryCreateResponseTest.kt @@ -0,0 +1,30 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class DirectoryCreateResponseTest { + + @Test + fun create() { + val directoryCreateResponse = DirectoryCreateResponse.builder().build() + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val directoryCreateResponse = DirectoryCreateResponse.builder().build() + + val roundtrippedDirectoryCreateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(directoryCreateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedDirectoryCreateResponse).isEqualTo(directoryCreateResponse) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DirectoryEventTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DirectoryEventTest.kt new file mode 100644 index 00000000..37a917e1 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DirectoryEventTest.kt @@ -0,0 +1,51 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class DirectoryEventTest { + + @Test + fun create() { + val directoryEvent = + DirectoryEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(DirectoryEvent.Data.builder().individualId("individual_id").build()) + .eventType(DirectoryEvent.EventType.DIRECTORY_CREATED) + .build() + + assertThat(directoryEvent.accountId()).isEqualTo("account_id") + assertThat(directoryEvent.companyId()).isEqualTo("company_id") + assertThat(directoryEvent.connectionId()).contains("connection_id") + assertThat(directoryEvent.data()) + .contains(DirectoryEvent.Data.builder().individualId("individual_id").build()) + assertThat(directoryEvent.eventType()).contains(DirectoryEvent.EventType.DIRECTORY_CREATED) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val directoryEvent = + DirectoryEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(DirectoryEvent.Data.builder().individualId("individual_id").build()) + .eventType(DirectoryEvent.EventType.DIRECTORY_CREATED) + .build() + + val roundtrippedDirectoryEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(directoryEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedDirectoryEvent).isEqualTo(directoryEvent) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DisconnectResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DisconnectResponseTest.kt index 9ff5e861..9975aadb 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DisconnectResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DisconnectResponseTest.kt @@ -2,15 +2,31 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class DisconnectResponseTest { +internal class DisconnectResponseTest { @Test - fun createDisconnectResponse() { + fun create() { val disconnectResponse = DisconnectResponse.builder().status("status").build() - assertThat(disconnectResponse).isNotNull + assertThat(disconnectResponse.status()).isEqualTo("status") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val disconnectResponse = DisconnectResponse.builder().status("status").build() + + val roundtrippedDisconnectResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(disconnectResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedDisconnectResponse).isEqualTo(disconnectResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DocumentListResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DocumentListResponseTest.kt index ace92517..a92d7839 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DocumentListResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DocumentListResponseTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class DocumentListResponseTest { +internal class DocumentListResponseTest { @Test - fun createDocumentListResponse() { + fun create() { val documentListResponse = DocumentListResponse.builder() .addDocument( @@ -22,7 +24,7 @@ class DocumentListResponseTest { ) .paging(Paging.builder().count(0L).offset(0L).build()) .build() - assertThat(documentListResponse).isNotNull + assertThat(documentListResponse.documents()) .containsExactly( DocumentResponse.builder() @@ -36,4 +38,30 @@ class DocumentListResponseTest { assertThat(documentListResponse.paging()) .isEqualTo(Paging.builder().count(0L).offset(0L).build()) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val documentListResponse = + DocumentListResponse.builder() + .addDocument( + DocumentResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .individualId("individual_id") + .type(DocumentResponse.Type.W4_2020) + .url("https://example.com") + .year(0.0) + .build() + ) + .paging(Paging.builder().count(0L).offset(0L).build()) + .build() + + val roundtrippedDocumentListResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(documentListResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedDocumentListResponse).isEqualTo(documentListResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DocumentResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DocumentResponseTest.kt index d138c11d..b44bd5da 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DocumentResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DocumentResponseTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class DocumentResponseTest { +internal class DocumentResponseTest { @Test - fun createDocumentResponse() { + fun create() { val documentResponse = DocumentResponse.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -17,11 +19,32 @@ class DocumentResponseTest { .url("https://example.com") .year(0.0) .build() - assertThat(documentResponse).isNotNull + assertThat(documentResponse.id()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(documentResponse.individualId()).contains("individual_id") assertThat(documentResponse.type()).contains(DocumentResponse.Type.W4_2020) assertThat(documentResponse.url()).contains("https://example.com") assertThat(documentResponse.year()).contains(0.0) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val documentResponse = + DocumentResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .individualId("individual_id") + .type(DocumentResponse.Type.W4_2020) + .url("https://example.com") + .year(0.0) + .build() + + val roundtrippedDocumentResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(documentResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedDocumentResponse).isEqualTo(documentResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DocumentRetreiveResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DocumentRetreiveResponseTest.kt new file mode 100644 index 00000000..acfd9553 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/DocumentRetreiveResponseTest.kt @@ -0,0 +1,144 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper +import com.tryfinch.api.errors.FinchInvalidDataException +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class DocumentRetreiveResponseTest { + + @Test + fun ofW42020() { + val w42020 = + W42020.builder() + .data( + W42020.Data.builder() + .amountForOtherDependents(0L) + .amountForQualifyingChildrenUnder17(0L) + .deductions(0L) + .extraWithholding(0L) + .filingStatus(W42020.Data.FilingStatus.HEAD_OF_HOUSEHOLD) + .individualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .otherIncome(0L) + .totalClaimDependentAndOtherCredits(0L) + .build() + ) + .type(W42020.Type.W4_2020) + .year(0.0) + .build() + + val documentRetreiveResponse = DocumentRetreiveResponse.ofW42020(w42020) + + assertThat(documentRetreiveResponse.w42020()).contains(w42020) + assertThat(documentRetreiveResponse.w42005()).isEmpty + } + + @Test + fun ofW42020Roundtrip() { + val jsonMapper = jsonMapper() + val documentRetreiveResponse = + DocumentRetreiveResponse.ofW42020( + W42020.builder() + .data( + W42020.Data.builder() + .amountForOtherDependents(0L) + .amountForQualifyingChildrenUnder17(0L) + .deductions(0L) + .extraWithholding(0L) + .filingStatus(W42020.Data.FilingStatus.HEAD_OF_HOUSEHOLD) + .individualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .otherIncome(0L) + .totalClaimDependentAndOtherCredits(0L) + .build() + ) + .type(W42020.Type.W4_2020) + .year(0.0) + .build() + ) + + val roundtrippedDocumentRetreiveResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(documentRetreiveResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedDocumentRetreiveResponse).isEqualTo(documentRetreiveResponse) + } + + @Test + fun ofW42005() { + val w42005 = + W42005.builder() + .data( + W42005.Data.builder() + .additionalWithholding(0L) + .exemption(W42005.Data.Exemption.EXEMPT) + .filingStatus(W42005.Data.FilingStatus.MARRIED) + .individualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .totalNumberOfAllowances(0L) + .build() + ) + .type(W42005.Type.W4_2005) + .year(0.0) + .build() + + val documentRetreiveResponse = DocumentRetreiveResponse.ofW42005(w42005) + + assertThat(documentRetreiveResponse.w42020()).isEmpty + assertThat(documentRetreiveResponse.w42005()).contains(w42005) + } + + @Test + fun ofW42005Roundtrip() { + val jsonMapper = jsonMapper() + val documentRetreiveResponse = + DocumentRetreiveResponse.ofW42005( + W42005.builder() + .data( + W42005.Data.builder() + .additionalWithholding(0L) + .exemption(W42005.Data.Exemption.EXEMPT) + .filingStatus(W42005.Data.FilingStatus.MARRIED) + .individualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .totalNumberOfAllowances(0L) + .build() + ) + .type(W42005.Type.W4_2005) + .year(0.0) + .build() + ) + + val roundtrippedDocumentRetreiveResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(documentRetreiveResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedDocumentRetreiveResponse).isEqualTo(documentRetreiveResponse) + } + + enum class IncompatibleJsonShapeTestCase(val value: JsonValue) { + BOOLEAN(JsonValue.from(false)), + STRING(JsonValue.from("invalid")), + INTEGER(JsonValue.from(-1)), + FLOAT(JsonValue.from(3.14)), + ARRAY(JsonValue.from(listOf("invalid", "array"))), + } + + @ParameterizedTest + @EnumSource + fun incompatibleJsonShapeDeserializesToUnknown(testCase: IncompatibleJsonShapeTestCase) { + val documentRetreiveResponse = + jsonMapper().convertValue(testCase.value, jacksonTypeRef()) + + val e = assertThrows { documentRetreiveResponse.validate() } + assertThat(e).hasMessageStartingWith("Unknown ") + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentDataResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentDataResponseTest.kt index e35bbacf..eb681174 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentDataResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentDataResponseTest.kt @@ -2,19 +2,21 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class EmploymentDataResponseTest { +internal class EmploymentDataResponseTest { @Test - fun createEmploymentDataResponse() { + fun create() { val employmentDataResponse = EmploymentDataResponse.builder() .body( EmploymentData.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .classCode("class_code") .addCustomField( EmploymentData.CustomField.builder() @@ -63,7 +65,11 @@ class EmploymentDataResponseTest { .state("state") .build() ) - .manager(EmploymentData.Manager.builder().id("id").build()) + .manager( + EmploymentData.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) .middleName("middle_name") .sourceId("source_id") .startDate("start_date") @@ -72,13 +78,13 @@ class EmploymentDataResponseTest { .build() ) .code(0L) - .individualId("individual_id") + .individualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(employmentDataResponse).isNotNull + assertThat(employmentDataResponse.body()) .contains( EmploymentData.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .classCode("class_code") .addCustomField( EmploymentData.CustomField.builder() @@ -127,7 +133,11 @@ class EmploymentDataResponseTest { .state("state") .build() ) - .manager(EmploymentData.Manager.builder().id("id").build()) + .manager( + EmploymentData.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) .middleName("middle_name") .sourceId("source_id") .startDate("start_date") @@ -136,6 +146,88 @@ class EmploymentDataResponseTest { .build() ) assertThat(employmentDataResponse.code()).contains(0L) - assertThat(employmentDataResponse.individualId()).contains("individual_id") + assertThat(employmentDataResponse.individualId()) + .contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val employmentDataResponse = + EmploymentDataResponse.builder() + .body( + EmploymentData.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .classCode("class_code") + .addCustomField( + EmploymentData.CustomField.builder() + .name("name") + .value(JsonValue.from(mapOf())) + .build() + ) + .department(EmploymentData.Department.builder().name("name").build()) + .employment( + EmploymentData.Employment.builder() + .subtype(EmploymentData.Employment.Subtype.FULL_TIME) + .type(EmploymentData.Employment.Type.EMPLOYEE) + .build() + ) + .employmentStatus(EmploymentData.EmploymentStatus.ACTIVE) + .endDate("end_date") + .firstName("first_name") + .income( + Income.builder() + .amount(0L) + .currency("currency") + .effectiveDate("effective_date") + .unit(Income.Unit.YEARLY) + .build() + ) + .addIncomeHistory( + Income.builder() + .amount(0L) + .currency("currency") + .effectiveDate("effective_date") + .unit(Income.Unit.YEARLY) + .build() + ) + .isActive(true) + .lastName("last_name") + .latestRehireDate("latest_rehire_date") + .location( + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() + ) + .manager( + EmploymentData.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .middleName("middle_name") + .sourceId("source_id") + .startDate("start_date") + .title("title") + .workId("work_id") + .build() + ) + .code(0L) + .individualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedEmploymentDataResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(employmentDataResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedEmploymentDataResponse).isEqualTo(employmentDataResponse) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentDataTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentDataTest.kt index 2eea0b0b..1cd072e8 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentDataTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentDataTest.kt @@ -2,17 +2,20 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class EmploymentDataTest { +internal class EmploymentDataTest { @Test - fun createEmploymentData() { + fun create() { val employmentData = EmploymentData.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .classCode("class_code") .addCustomField( EmploymentData.CustomField.builder() @@ -61,17 +64,21 @@ class EmploymentDataTest { .state("state") .build() ) - .manager(EmploymentData.Manager.builder().id("id").build()) + .manager( + EmploymentData.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) .middleName("middle_name") .sourceId("source_id") .startDate("start_date") .title("title") .workId("work_id") .build() - assertThat(employmentData).isNotNull - assertThat(employmentData.id()).contains("id") + + assertThat(employmentData.id()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(employmentData.classCode()).contains("class_code") - assertThat(employmentData.customFields().get()) + assertThat(employmentData.customFields().getOrNull()) .containsExactly( EmploymentData.CustomField.builder() .name("name") @@ -100,7 +107,7 @@ class EmploymentDataTest { .unit(Income.Unit.YEARLY) .build() ) - assertThat(employmentData.incomeHistory().get()) + assertThat(employmentData.incomeHistory().getOrNull()) .containsExactly( Income.builder() .amount(0L) @@ -126,11 +133,88 @@ class EmploymentDataTest { .build() ) assertThat(employmentData.manager()) - .contains(EmploymentData.Manager.builder().id("id").build()) + .contains( + EmploymentData.Manager.builder().id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + ) assertThat(employmentData.middleName()).contains("middle_name") assertThat(employmentData.sourceId()).contains("source_id") assertThat(employmentData.startDate()).contains("start_date") assertThat(employmentData.title()).contains("title") assertThat(employmentData.workId()).contains("work_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val employmentData = + EmploymentData.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .classCode("class_code") + .addCustomField( + EmploymentData.CustomField.builder() + .name("name") + .value(JsonValue.from(mapOf())) + .build() + ) + .department(EmploymentData.Department.builder().name("name").build()) + .employment( + EmploymentData.Employment.builder() + .subtype(EmploymentData.Employment.Subtype.FULL_TIME) + .type(EmploymentData.Employment.Type.EMPLOYEE) + .build() + ) + .employmentStatus(EmploymentData.EmploymentStatus.ACTIVE) + .endDate("end_date") + .firstName("first_name") + .income( + Income.builder() + .amount(0L) + .currency("currency") + .effectiveDate("effective_date") + .unit(Income.Unit.YEARLY) + .build() + ) + .addIncomeHistory( + Income.builder() + .amount(0L) + .currency("currency") + .effectiveDate("effective_date") + .unit(Income.Unit.YEARLY) + .build() + ) + .isActive(true) + .lastName("last_name") + .latestRehireDate("latest_rehire_date") + .location( + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() + ) + .manager( + EmploymentData.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .middleName("middle_name") + .sourceId("source_id") + .startDate("start_date") + .title("title") + .workId("work_id") + .build() + + val roundtrippedEmploymentData = + jsonMapper.readValue( + jsonMapper.writeValueAsString(employmentData), + jacksonTypeRef(), + ) + + assertThat(roundtrippedEmploymentData).isEqualTo(employmentData) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentEventTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentEventTest.kt new file mode 100644 index 00000000..30a66f97 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentEventTest.kt @@ -0,0 +1,52 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class EmploymentEventTest { + + @Test + fun create() { + val employmentEvent = + EmploymentEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(EmploymentEvent.Data.builder().individualId("individual_id").build()) + .eventType(EmploymentEvent.EventType.EMPLOYMENT_CREATED) + .build() + + assertThat(employmentEvent.accountId()).isEqualTo("account_id") + assertThat(employmentEvent.companyId()).isEqualTo("company_id") + assertThat(employmentEvent.connectionId()).contains("connection_id") + assertThat(employmentEvent.data()) + .contains(EmploymentEvent.Data.builder().individualId("individual_id").build()) + assertThat(employmentEvent.eventType()) + .contains(EmploymentEvent.EventType.EMPLOYMENT_CREATED) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val employmentEvent = + EmploymentEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(EmploymentEvent.Data.builder().individualId("individual_id").build()) + .eventType(EmploymentEvent.EventType.EMPLOYMENT_CREATED) + .build() + + val roundtrippedEmploymentEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(employmentEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedEmploymentEvent).isEqualTo(employmentEvent) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentUpdateResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentUpdateResponseTest.kt index 282c47ae..36d22b27 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentUpdateResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EmploymentUpdateResponseTest.kt @@ -2,17 +2,20 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class EmploymentUpdateResponseTest { +internal class EmploymentUpdateResponseTest { @Test - fun createEmploymentUpdateResponse() { + fun create() { val employmentUpdateResponse = EmploymentUpdateResponse.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .classCode("class_code") .addCustomField( EmploymentUpdateResponse.CustomField.builder() @@ -61,16 +64,20 @@ class EmploymentUpdateResponseTest { .state("state") .build() ) - .manager(EmploymentUpdateResponse.Manager.builder().id("id").build()) + .manager( + EmploymentUpdateResponse.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) .middleName("middle_name") .sourceId("source_id") .startDate("start_date") .title("title") .build() - assertThat(employmentUpdateResponse).isNotNull - assertThat(employmentUpdateResponse.id()).contains("id") + + assertThat(employmentUpdateResponse.id()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(employmentUpdateResponse.classCode()).contains("class_code") - assertThat(employmentUpdateResponse.customFields().get()) + assertThat(employmentUpdateResponse.customFields().getOrNull()) .containsExactly( EmploymentUpdateResponse.CustomField.builder() .name("name") @@ -99,7 +106,7 @@ class EmploymentUpdateResponseTest { .unit(Income.Unit.YEARLY) .build() ) - assertThat(employmentUpdateResponse.incomeHistory().get()) + assertThat(employmentUpdateResponse.incomeHistory().getOrNull()) .containsExactly( Income.builder() .amount(0L) @@ -125,10 +132,88 @@ class EmploymentUpdateResponseTest { .build() ) assertThat(employmentUpdateResponse.manager()) - .contains(EmploymentUpdateResponse.Manager.builder().id("id").build()) + .contains( + EmploymentUpdateResponse.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) assertThat(employmentUpdateResponse.middleName()).contains("middle_name") assertThat(employmentUpdateResponse.sourceId()).contains("source_id") assertThat(employmentUpdateResponse.startDate()).contains("start_date") assertThat(employmentUpdateResponse.title()).contains("title") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val employmentUpdateResponse = + EmploymentUpdateResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .classCode("class_code") + .addCustomField( + EmploymentUpdateResponse.CustomField.builder() + .name("name") + .value(JsonValue.from(mapOf())) + .build() + ) + .department(EmploymentUpdateResponse.Department.builder().name("name").build()) + .employment( + EmploymentUpdateResponse.Employment.builder() + .subtype(EmploymentUpdateResponse.Employment.Subtype.FULL_TIME) + .type(EmploymentUpdateResponse.Employment.Type.EMPLOYEE) + .build() + ) + .employmentStatus(EmploymentUpdateResponse.EmploymentStatus.ACTIVE) + .endDate("end_date") + .firstName("first_name") + .income( + Income.builder() + .amount(0L) + .currency("currency") + .effectiveDate("effective_date") + .unit(Income.Unit.YEARLY) + .build() + ) + .addIncomeHistory( + Income.builder() + .amount(0L) + .currency("currency") + .effectiveDate("effective_date") + .unit(Income.Unit.YEARLY) + .build() + ) + .isActive(true) + .lastName("last_name") + .latestRehireDate("latest_rehire_date") + .location( + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() + ) + .manager( + EmploymentUpdateResponse.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .middleName("middle_name") + .sourceId("source_id") + .startDate("start_date") + .title("title") + .build() + + val roundtrippedEmploymentUpdateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(employmentUpdateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedEmploymentUpdateResponse).isEqualTo(employmentUpdateResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EnrolledIndividualTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EnrolledIndividualTest.kt index 0613d04c..73c9547e 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EnrolledIndividualTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/EnrolledIndividualTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class EnrolledIndividualTest { +internal class EnrolledIndividualTest { @Test - fun createEnrolledIndividual() { + fun create() { val enrolledIndividual = EnrolledIndividual.builder() .body( @@ -21,7 +23,7 @@ class EnrolledIndividualTest { .code(EnrolledIndividual.Code.OK) .individualId("individual_id") .build() - assertThat(enrolledIndividual).isNotNull + assertThat(enrolledIndividual.body()) .contains( EnrolledIndividual.Body.builder() @@ -33,4 +35,29 @@ class EnrolledIndividualTest { assertThat(enrolledIndividual.code()).contains(EnrolledIndividual.Code.OK) assertThat(enrolledIndividual.individualId()).contains("individual_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val enrolledIndividual = + EnrolledIndividual.builder() + .body( + EnrolledIndividual.Body.builder() + .finchCode("finch_code") + .message("message") + .name("name") + .build() + ) + .code(EnrolledIndividual.Code.OK) + .individualId("individual_id") + .build() + + val roundtrippedEnrolledIndividual = + jsonMapper.readValue( + jsonMapper.writeValueAsString(enrolledIndividual), + jacksonTypeRef(), + ) + + assertThat(roundtrippedEnrolledIndividual).isEqualTo(enrolledIndividual) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitCreateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitCreateParamsTest.kt index 8255a9c7..fea44e47 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitCreateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitCreateParamsTest.kt @@ -2,11 +2,10 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisBenefitCreateParamsTest { +internal class HrisBenefitCreateParamsTest { @Test fun create() { @@ -28,7 +27,6 @@ class HrisBenefitCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.description()).contains("description") assertThat(body.frequency()).contains(BenefitFrequency.ONE_TIME) assertThat(body.type()).contains(BenefitType._401K) @@ -39,7 +37,5 @@ class HrisBenefitCreateParamsTest { val params = HrisBenefitCreateParams.builder().build() val body = params._body() - - assertNotNull(body) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitIndividualEnrolledIdsParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitIndividualEnrolledIdsParamsTest.kt index de75d8dc..5226e6c1 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitIndividualEnrolledIdsParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitIndividualEnrolledIdsParamsTest.kt @@ -5,7 +5,7 @@ package com.tryfinch.api.models import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisBenefitIndividualEnrolledIdsParamsTest { +internal class HrisBenefitIndividualEnrolledIdsParamsTest { @Test fun create() { @@ -13,13 +13,12 @@ class HrisBenefitIndividualEnrolledIdsParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = HrisBenefitIndividualEnrolledIdsParams.builder().benefitId("benefit_id").build() - assertThat(params).isNotNull - // path param "benefitId" - assertThat(params.getPathParam(0)).isEqualTo("benefit_id") + + assertThat(params._pathParam(0)).isEqualTo("benefit_id") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsParamsTest.kt index 5768f00c..fbd9e20a 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitIndividualRetrieveManyBenefitsParamsTest.kt @@ -6,7 +6,7 @@ import com.tryfinch.api.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisBenefitIndividualRetrieveManyBenefitsParamsTest { +internal class HrisBenefitIndividualRetrieveManyBenefitsParamsTest { @Test fun create() { @@ -19,42 +19,49 @@ class HrisBenefitIndividualRetrieveManyBenefitsParamsTest { } @Test - fun queryParams() { + fun pathParams() { val params = HrisBenefitIndividualRetrieveManyBenefitsParams.builder() .benefitId("benefit_id") - .individualIds( - "d675d2b7-6d7b-41a8-b2d3-001eb3fb88f6,d02a6346-1f08-4312-a064-49ff3cafaa7a" - ) .build() - val expected = QueryParams.builder() - expected.put( - "individual_ids", - "d675d2b7-6d7b-41a8-b2d3-001eb3fb88f6,d02a6346-1f08-4312-a064-49ff3cafaa7a", - ) - assertThat(params._queryParams()).isEqualTo(expected.build()) + + assertThat(params._pathParam(0)).isEqualTo("benefit_id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun queryParamsWithoutOptionalFields() { + fun queryParams() { val params = HrisBenefitIndividualRetrieveManyBenefitsParams.builder() .benefitId("benefit_id") + .individualIds( + "d675d2b7-6d7b-41a8-b2d3-001eb3fb88f6,d02a6346-1f08-4312-a064-49ff3cafaa7a" + ) .build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put( + "individual_ids", + "d675d2b7-6d7b-41a8-b2d3-001eb3fb88f6,d02a6346-1f08-4312-a064-49ff3cafaa7a", + ) + .build() + ) } @Test - fun getPathParam() { + fun queryParamsWithoutOptionalFields() { val params = HrisBenefitIndividualRetrieveManyBenefitsParams.builder() .benefitId("benefit_id") .build() - assertThat(params).isNotNull - // path param "benefitId" - assertThat(params.getPathParam(0)).isEqualTo("benefit_id") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyParamsTest.kt index 9e007c2a..ee438af1 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitIndividualUnenrollManyParamsTest.kt @@ -2,11 +2,11 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisBenefitIndividualUnenrollManyParamsTest { +internal class HrisBenefitIndividualUnenrollManyParamsTest { @Test fun create() { @@ -16,6 +16,16 @@ class HrisBenefitIndividualUnenrollManyParamsTest { .build() } + @Test + fun pathParams() { + val params = + HrisBenefitIndividualUnenrollManyParams.builder().benefitId("benefit_id").build() + + assertThat(params._pathParam(0)).isEqualTo("benefit_id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -26,8 +36,7 @@ class HrisBenefitIndividualUnenrollManyParamsTest { val body = params._body() - assertNotNull(body) - assertThat(body.individualIds()).contains(listOf("string")) + assertThat(body.individualIds().getOrNull()).containsExactly("string") } @Test @@ -36,18 +45,5 @@ class HrisBenefitIndividualUnenrollManyParamsTest { HrisBenefitIndividualUnenrollManyParams.builder().benefitId("benefit_id").build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = - HrisBenefitIndividualUnenrollManyParams.builder().benefitId("benefit_id").build() - assertThat(params).isNotNull - // path param "benefitId" - assertThat(params.getPathParam(0)).isEqualTo("benefit_id") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitListParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitListParamsTest.kt index 587d8917..09d50f7e 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitListParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitListParamsTest.kt @@ -4,7 +4,7 @@ package com.tryfinch.api.models import org.junit.jupiter.api.Test -class HrisBenefitListParamsTest { +internal class HrisBenefitListParamsTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsParamsTest.kt index 5aaf456f..c9e4aa6c 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitListSupportedBenefitsParamsTest.kt @@ -4,7 +4,7 @@ package com.tryfinch.api.models import org.junit.jupiter.api.Test -class HrisBenefitListSupportedBenefitsParamsTest { +internal class HrisBenefitListSupportedBenefitsParamsTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitRetrieveParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitRetrieveParamsTest.kt index ca7ecf00..7b1d62f4 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitRetrieveParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitRetrieveParamsTest.kt @@ -5,7 +5,7 @@ package com.tryfinch.api.models import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisBenefitRetrieveParamsTest { +internal class HrisBenefitRetrieveParamsTest { @Test fun create() { @@ -13,12 +13,11 @@ class HrisBenefitRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = HrisBenefitRetrieveParams.builder().benefitId("benefit_id").build() - assertThat(params).isNotNull - // path param "benefitId" - assertThat(params.getPathParam(0)).isEqualTo("benefit_id") + + assertThat(params._pathParam(0)).isEqualTo("benefit_id") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitUpdateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitUpdateParamsTest.kt index b9074f26..d2c29113 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitUpdateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisBenefitUpdateParamsTest.kt @@ -2,17 +2,25 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisBenefitUpdateParamsTest { +internal class HrisBenefitUpdateParamsTest { @Test fun create() { HrisBenefitUpdateParams.builder().benefitId("benefit_id").description("description").build() } + @Test + fun pathParams() { + val params = HrisBenefitUpdateParams.builder().benefitId("benefit_id").build() + + assertThat(params._pathParam(0)).isEqualTo("benefit_id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -23,7 +31,6 @@ class HrisBenefitUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.description()).contains("description") } @@ -32,17 +39,5 @@ class HrisBenefitUpdateParamsTest { val params = HrisBenefitUpdateParams.builder().benefitId("benefit_id").build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = HrisBenefitUpdateParams.builder().benefitId("benefit_id").build() - assertThat(params).isNotNull - // path param "benefitId" - assertThat(params.getPathParam(0)).isEqualTo("benefit_id") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemListParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemListParamsTest.kt new file mode 100644 index 00000000..f96974b4 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemListParamsTest.kt @@ -0,0 +1,56 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.tryfinch.api.core.http.QueryParams +import java.time.LocalDate +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class HrisCompanyPayStatementItemListParamsTest { + + @Test + fun create() { + HrisCompanyPayStatementItemListParams.builder() + .addCategory(HrisCompanyPayStatementItemListParams.Category.EARNINGS) + .endDate(LocalDate.parse("2024-07-01")) + .name("name") + .startDate(LocalDate.parse("2024-01-01")) + .type("base_compensation") + .build() + } + + @Test + fun queryParams() { + val params = + HrisCompanyPayStatementItemListParams.builder() + .addCategory(HrisCompanyPayStatementItemListParams.Category.EARNINGS) + .endDate(LocalDate.parse("2024-07-01")) + .name("name") + .startDate(LocalDate.parse("2024-01-01")) + .type("base_compensation") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("categories[]", "earnings") + .put("end_date", "2024-07-01") + .put("name", "name") + .put("start_date", "2024-01-01") + .put("type", "base_compensation") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = HrisCompanyPayStatementItemListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleCreateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleCreateParamsTest.kt new file mode 100644 index 00000000..aaafb200 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleCreateParamsTest.kt @@ -0,0 +1,99 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.tryfinch.api.core.JsonValue +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class HrisCompanyPayStatementItemRuleCreateParamsTest { + + @Test + fun create() { + HrisCompanyPayStatementItemRuleCreateParams.builder() + .attributes( + HrisCompanyPayStatementItemRuleCreateParams.Attributes.builder() + .metadata( + HrisCompanyPayStatementItemRuleCreateParams.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .addCondition( + HrisCompanyPayStatementItemRuleCreateParams.Condition.builder() + .field("field") + .operator(HrisCompanyPayStatementItemRuleCreateParams.Condition.Operator.EQUALS) + .value("value") + .build() + ) + .effectiveEndDate("effective_end_date") + .effectiveStartDate("effective_start_date") + .entityType(HrisCompanyPayStatementItemRuleCreateParams.EntityType.PAY_STATEMENT_ITEM) + .build() + } + + @Test + fun body() { + val params = + HrisCompanyPayStatementItemRuleCreateParams.builder() + .attributes( + HrisCompanyPayStatementItemRuleCreateParams.Attributes.builder() + .metadata( + HrisCompanyPayStatementItemRuleCreateParams.Attributes.Metadata + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .addCondition( + HrisCompanyPayStatementItemRuleCreateParams.Condition.builder() + .field("field") + .operator( + HrisCompanyPayStatementItemRuleCreateParams.Condition.Operator.EQUALS + ) + .value("value") + .build() + ) + .effectiveEndDate("effective_end_date") + .effectiveStartDate("effective_start_date") + .entityType( + HrisCompanyPayStatementItemRuleCreateParams.EntityType.PAY_STATEMENT_ITEM + ) + .build() + + val body = params._body() + + assertThat(body.attributes()) + .contains( + HrisCompanyPayStatementItemRuleCreateParams.Attributes.builder() + .metadata( + HrisCompanyPayStatementItemRuleCreateParams.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + assertThat(body.conditions().getOrNull()) + .containsExactly( + HrisCompanyPayStatementItemRuleCreateParams.Condition.builder() + .field("field") + .operator(HrisCompanyPayStatementItemRuleCreateParams.Condition.Operator.EQUALS) + .value("value") + .build() + ) + assertThat(body.effectiveEndDate()).contains("effective_end_date") + assertThat(body.effectiveStartDate()).contains("effective_start_date") + assertThat(body.entityType()) + .contains(HrisCompanyPayStatementItemRuleCreateParams.EntityType.PAY_STATEMENT_ITEM) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = HrisCompanyPayStatementItemRuleCreateParams.builder().build() + + val body = params._body() + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleDeleteParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleDeleteParamsTest.kt new file mode 100644 index 00000000..803a0650 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleDeleteParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class HrisCompanyPayStatementItemRuleDeleteParamsTest { + + @Test + fun create() { + HrisCompanyPayStatementItemRuleDeleteParams.builder().ruleId("rule_id").build() + } + + @Test + fun pathParams() { + val params = HrisCompanyPayStatementItemRuleDeleteParams.builder().ruleId("rule_id").build() + + assertThat(params._pathParam(0)).isEqualTo("rule_id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleListParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleListParamsTest.kt new file mode 100644 index 00000000..05fa5101 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleListParamsTest.kt @@ -0,0 +1,13 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import org.junit.jupiter.api.Test + +internal class HrisCompanyPayStatementItemRuleListParamsTest { + + @Test + fun create() { + HrisCompanyPayStatementItemRuleListParams.builder().build() + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleUpdateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleUpdateParamsTest.kt new file mode 100644 index 00000000..9243af8c --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyPayStatementItemRuleUpdateParamsTest.kt @@ -0,0 +1,47 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.tryfinch.api.core.JsonValue +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class HrisCompanyPayStatementItemRuleUpdateParamsTest { + + @Test + fun create() { + HrisCompanyPayStatementItemRuleUpdateParams.builder() + .ruleId("rule_id") + .optionalProperty(JsonValue.from(mapOf())) + .build() + } + + @Test + fun pathParams() { + val params = HrisCompanyPayStatementItemRuleUpdateParams.builder().ruleId("rule_id").build() + + assertThat(params._pathParam(0)).isEqualTo("rule_id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + + @Test + fun body() { + val params = + HrisCompanyPayStatementItemRuleUpdateParams.builder() + .ruleId("rule_id") + .optionalProperty(JsonValue.from(mapOf())) + .build() + + val body = params._body() + + assertThat(body._optionalProperty()).isEqualTo(JsonValue.from(mapOf())) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = HrisCompanyPayStatementItemRuleUpdateParams.builder().ruleId("rule_id").build() + + val body = params._body() + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyRetrieveParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyRetrieveParamsTest.kt index ba444bb0..d96e46dd 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyRetrieveParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisCompanyRetrieveParamsTest.kt @@ -4,7 +4,7 @@ package com.tryfinch.api.models import org.junit.jupiter.api.Test -class HrisCompanyRetrieveParamsTest { +internal class HrisCompanyRetrieveParamsTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsParamsTest.kt index 42efb8a4..340e2a6b 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDirectoryListIndividualsParamsTest.kt @@ -6,7 +6,7 @@ import com.tryfinch.api.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisDirectoryListIndividualsParamsTest { +internal class HrisDirectoryListIndividualsParamsTest { @Test fun create() { @@ -16,16 +16,19 @@ class HrisDirectoryListIndividualsParamsTest { @Test fun queryParams() { val params = HrisDirectoryListIndividualsParams.builder().limit(0L).offset(0L).build() - val expected = QueryParams.builder() - expected.put("limit", "0") - expected.put("offset", "0") - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo(QueryParams.builder().put("limit", "0").put("offset", "0").build()) } @Test fun queryParamsWithoutOptionalFields() { val params = HrisDirectoryListIndividualsParams.builder().build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDirectoryListParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDirectoryListParamsTest.kt index fdfd708a..01611811 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDirectoryListParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDirectoryListParamsTest.kt @@ -6,7 +6,7 @@ import com.tryfinch.api.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisDirectoryListParamsTest { +internal class HrisDirectoryListParamsTest { @Test fun create() { @@ -16,16 +16,19 @@ class HrisDirectoryListParamsTest { @Test fun queryParams() { val params = HrisDirectoryListParams.builder().limit(0L).offset(0L).build() - val expected = QueryParams.builder() - expected.put("limit", "0") - expected.put("offset", "0") - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo(QueryParams.builder().put("limit", "0").put("offset", "0").build()) } @Test fun queryParamsWithoutOptionalFields() { val params = HrisDirectoryListParams.builder().build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDocumentListParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDocumentListParamsTest.kt index 4b3093ef..bc450bba 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDocumentListParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDocumentListParamsTest.kt @@ -6,7 +6,7 @@ import com.tryfinch.api.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisDocumentListParamsTest { +internal class HrisDocumentListParamsTest { @Test fun create() { @@ -27,18 +27,26 @@ class HrisDocumentListParamsTest { .offset(0L) .addType(HrisDocumentListParams.Type.W4_2020) .build() - val expected = QueryParams.builder() - expected.put("individual_ids[]", "string") - expected.put("limit", "0") - expected.put("offset", "0") - expected.put("types[]", HrisDocumentListParams.Type.W4_2020.toString()) - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("individual_ids[]", "string") + .put("limit", "0") + .put("offset", "0") + .put("types[]", "w4_2020") + .build() + ) } @Test fun queryParamsWithoutOptionalFields() { val params = HrisDocumentListParams.builder().build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDocumentRetreiveParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDocumentRetreiveParamsTest.kt index 89a0e4c9..3fbc4678 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDocumentRetreiveParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisDocumentRetreiveParamsTest.kt @@ -5,7 +5,7 @@ package com.tryfinch.api.models import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisDocumentRetreiveParamsTest { +internal class HrisDocumentRetreiveParamsTest { @Test fun create() { @@ -13,12 +13,11 @@ class HrisDocumentRetreiveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = HrisDocumentRetreiveParams.builder().documentId("document_id").build() - assertThat(params).isNotNull - // path param "documentId" - assertThat(params.getPathParam(0)).isEqualTo("document_id") + + assertThat(params._pathParam(0)).isEqualTo("document_id") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyParamsTest.kt index c1b825d6..89232ae6 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisEmploymentRetrieveManyParamsTest.kt @@ -2,11 +2,10 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisEmploymentRetrieveManyParamsTest { +internal class HrisEmploymentRetrieveManyParamsTest { @Test fun create() { @@ -32,38 +31,11 @@ class HrisEmploymentRetrieveManyParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.requests()) - .isEqualTo( - listOf( - HrisEmploymentRetrieveManyParams.Request.builder() - .individualId("individual_id") - .build() - ) - ) - } - - @Test - fun bodyWithoutOptionalFields() { - val params = - HrisEmploymentRetrieveManyParams.builder() - .addRequest( - HrisEmploymentRetrieveManyParams.Request.builder() - .individualId("individual_id") - .build() - ) - .build() - - val body = params._body() - - assertNotNull(body) - assertThat(body.requests()) - .isEqualTo( - listOf( - HrisEmploymentRetrieveManyParams.Request.builder() - .individualId("individual_id") - .build() - ) + .containsExactly( + HrisEmploymentRetrieveManyParams.Request.builder() + .individualId("individual_id") + .build() ) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyParamsTest.kt index 34340368..141495c8 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyParamsTest.kt @@ -2,11 +2,11 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisIndividualRetrieveManyParamsTest { +internal class HrisIndividualRetrieveManyParamsTest { @Test fun create() { @@ -38,18 +38,15 @@ class HrisIndividualRetrieveManyParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.options()) .contains( HrisIndividualRetrieveManyParams.Options.builder().addInclude("string").build() ) - assertThat(body.requests()) - .contains( - listOf( - HrisIndividualRetrieveManyParams.Request.builder() - .individualId("individual_id") - .build() - ) + assertThat(body.requests().getOrNull()) + .containsExactly( + HrisIndividualRetrieveManyParams.Request.builder() + .individualId("individual_id") + .build() ) } @@ -58,7 +55,5 @@ class HrisIndividualRetrieveManyParamsTest { val params = HrisIndividualRetrieveManyParams.builder().build() val body = params._body() - - assertNotNull(body) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyParamsTest.kt index da6b1ccd..f7e8edfa 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisPayStatementRetrieveManyParamsTest.kt @@ -2,18 +2,17 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisPayStatementRetrieveManyParamsTest { +internal class HrisPayStatementRetrieveManyParamsTest { @Test fun create() { HrisPayStatementRetrieveManyParams.builder() .addRequest( HrisPayStatementRetrieveManyParams.Request.builder() - .paymentId("string") + .paymentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .limit(50L) .offset(0L) .build() @@ -27,7 +26,7 @@ class HrisPayStatementRetrieveManyParamsTest { HrisPayStatementRetrieveManyParams.builder() .addRequest( HrisPayStatementRetrieveManyParams.Request.builder() - .paymentId("string") + .paymentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .limit(50L) .offset(0L) .build() @@ -36,16 +35,13 @@ class HrisPayStatementRetrieveManyParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.requests()) - .isEqualTo( - listOf( - HrisPayStatementRetrieveManyParams.Request.builder() - .paymentId("string") - .limit(50L) - .offset(0L) - .build() - ) + .containsExactly( + HrisPayStatementRetrieveManyParams.Request.builder() + .paymentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(50L) + .offset(0L) + .build() ) } @@ -54,18 +50,19 @@ class HrisPayStatementRetrieveManyParamsTest { val params = HrisPayStatementRetrieveManyParams.builder() .addRequest( - HrisPayStatementRetrieveManyParams.Request.builder().paymentId("string").build() + HrisPayStatementRetrieveManyParams.Request.builder() + .paymentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() ) .build() val body = params._body() - assertNotNull(body) assertThat(body.requests()) - .isEqualTo( - listOf( - HrisPayStatementRetrieveManyParams.Request.builder().paymentId("string").build() - ) + .containsExactly( + HrisPayStatementRetrieveManyParams.Request.builder() + .paymentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() ) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisPaymentListParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisPaymentListParamsTest.kt index 573bdb2c..f07f49c4 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisPaymentListParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisPaymentListParamsTest.kt @@ -7,7 +7,7 @@ import java.time.LocalDate import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class HrisPaymentListParamsTest { +internal class HrisPaymentListParamsTest { @Test fun create() { @@ -24,22 +24,15 @@ class HrisPaymentListParamsTest { .endDate(LocalDate.parse("2021-01-01")) .startDate(LocalDate.parse("2021-01-01")) .build() - val expected = QueryParams.builder() - expected.put("end_date", "2021-01-01") - expected.put("start_date", "2021-01-01") - assertThat(params._queryParams()).isEqualTo(expected.build()) - } - @Test - fun queryParamsWithoutOptionalFields() { - val params = - HrisPaymentListParams.builder() - .endDate(LocalDate.parse("2021-01-01")) - .startDate(LocalDate.parse("2021-01-01")) - .build() - val expected = QueryParams.builder() - expected.put("end_date", "2021-01-01") - expected.put("start_date", "2021-01-01") - assertThat(params._queryParams()).isEqualTo(expected.build()) + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("end_date", "2021-01-01") + .put("start_date", "2021-01-01") + .build() + ) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IncomeTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IncomeTest.kt index 48189257..f50c94ec 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IncomeTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IncomeTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class IncomeTest { +internal class IncomeTest { @Test - fun createIncome() { + fun create() { val income = Income.builder() .amount(0L) @@ -16,10 +18,27 @@ class IncomeTest { .effectiveDate("effective_date") .unit(Income.Unit.YEARLY) .build() - assertThat(income).isNotNull + assertThat(income.amount()).contains(0L) assertThat(income.currency()).contains("currency") assertThat(income.effectiveDate()).contains("effective_date") assertThat(income.unit()).contains(Income.Unit.YEARLY) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val income = + Income.builder() + .amount(0L) + .currency("currency") + .effectiveDate("effective_date") + .unit(Income.Unit.YEARLY) + .build() + + val roundtrippedIncome = + jsonMapper.readValue(jsonMapper.writeValueAsString(income), jacksonTypeRef()) + + assertThat(roundtrippedIncome).isEqualTo(income) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualBenefitTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualBenefitTest.kt index 64fda15d..3b912383 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualBenefitTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualBenefitTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class IndividualBenefitTest { +internal class IndividualBenefitTest { @Test - fun createIndividualBenefit() { + fun create() { val individualBenefit = IndividualBenefit.builder() .body( @@ -35,7 +37,7 @@ class IndividualBenefitTest { .code(0L) .individualId("individual_id") .build() - assertThat(individualBenefit).isNotNull + assertThat(individualBenefit.body()) .contains( IndividualBenefit.Body.builder() @@ -59,4 +61,43 @@ class IndividualBenefitTest { assertThat(individualBenefit.code()).contains(0L) assertThat(individualBenefit.individualId()).contains("individual_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val individualBenefit = + IndividualBenefit.builder() + .body( + IndividualBenefit.Body.builder() + .annualMaximum(0L) + .catchUp(true) + .companyContribution( + BenefitContribution.builder() + .amount(0L) + .type(BenefitContribution.Type.FIXED) + .build() + ) + .employeeDeduction( + BenefitContribution.builder() + .amount(0L) + .type(BenefitContribution.Type.FIXED) + .build() + ) + .hsaContributionLimit( + IndividualBenefit.Body.HsaContributionLimit.INDIVIDUAL + ) + .build() + ) + .code(0L) + .individualId("individual_id") + .build() + + val roundtrippedIndividualBenefit = + jsonMapper.readValue( + jsonMapper.writeValueAsString(individualBenefit), + jacksonTypeRef(), + ) + + assertThat(roundtrippedIndividualBenefit).isEqualTo(individualBenefit) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualEnrolledIdsResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualEnrolledIdsResponseTest.kt index 02aedfcf..5267cd8e 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualEnrolledIdsResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualEnrolledIdsResponseTest.kt @@ -2,20 +2,43 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class IndividualEnrolledIdsResponseTest { +internal class IndividualEnrolledIdsResponseTest { @Test - fun createIndividualEnrolledIdsResponse() { + fun create() { val individualEnrolledIdsResponse = IndividualEnrolledIdsResponse.builder() - .benefitId("benefit_id") - .addIndividualId("string") + .benefitId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addIndividualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(individualEnrolledIdsResponse).isNotNull - assertThat(individualEnrolledIdsResponse.benefitId()).isEqualTo("benefit_id") - assertThat(individualEnrolledIdsResponse.individualIds()).containsExactly("string") + + assertThat(individualEnrolledIdsResponse.benefitId()) + .isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(individualEnrolledIdsResponse.individualIds()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val individualEnrolledIdsResponse = + IndividualEnrolledIdsResponse.builder() + .benefitId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addIndividualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedIndividualEnrolledIdsResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(individualEnrolledIdsResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedIndividualEnrolledIdsResponse) + .isEqualTo(individualEnrolledIdsResponse) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualEventTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualEventTest.kt new file mode 100644 index 00000000..3909ed85 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualEventTest.kt @@ -0,0 +1,52 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class IndividualEventTest { + + @Test + fun create() { + val individualEvent = + IndividualEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(IndividualEvent.Data.builder().individualId("individual_id").build()) + .eventType(IndividualEvent.EventType.INDIVIDUAL_CREATED) + .build() + + assertThat(individualEvent.accountId()).isEqualTo("account_id") + assertThat(individualEvent.companyId()).isEqualTo("company_id") + assertThat(individualEvent.connectionId()).contains("connection_id") + assertThat(individualEvent.data()) + .contains(IndividualEvent.Data.builder().individualId("individual_id").build()) + assertThat(individualEvent.eventType()) + .contains(IndividualEvent.EventType.INDIVIDUAL_CREATED) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val individualEvent = + IndividualEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(IndividualEvent.Data.builder().individualId("individual_id").build()) + .eventType(IndividualEvent.EventType.INDIVIDUAL_CREATED) + .build() + + val roundtrippedIndividualEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(individualEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedIndividualEvent).isEqualTo(individualEvent) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualInDirectoryTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualInDirectoryTest.kt index e812e2d1..dc8f18ea 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualInDirectoryTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualInDirectoryTest.kt @@ -2,32 +2,69 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class IndividualInDirectoryTest { +internal class IndividualInDirectoryTest { @Test - fun createIndividualInDirectory() { + fun create() { val individualInDirectory = IndividualInDirectory.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .department(IndividualInDirectory.Department.builder().name("name").build()) .firstName("first_name") .isActive(true) .lastName("last_name") - .manager(IndividualInDirectory.Manager.builder().id("id").build()) + .manager( + IndividualInDirectory.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) .middleName("middle_name") .build() - assertThat(individualInDirectory).isNotNull - assertThat(individualInDirectory.id()).contains("id") + + assertThat(individualInDirectory.id()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(individualInDirectory.department()) .contains(IndividualInDirectory.Department.builder().name("name").build()) assertThat(individualInDirectory.firstName()).contains("first_name") assertThat(individualInDirectory.isActive()).contains(true) assertThat(individualInDirectory.lastName()).contains("last_name") assertThat(individualInDirectory.manager()) - .contains(IndividualInDirectory.Manager.builder().id("id").build()) + .contains( + IndividualInDirectory.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) assertThat(individualInDirectory.middleName()).contains("middle_name") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val individualInDirectory = + IndividualInDirectory.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .department(IndividualInDirectory.Department.builder().name("name").build()) + .firstName("first_name") + .isActive(true) + .lastName("last_name") + .manager( + IndividualInDirectory.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .middleName("middle_name") + .build() + + val roundtrippedIndividualInDirectory = + jsonMapper.readValue( + jsonMapper.writeValueAsString(individualInDirectory), + jacksonTypeRef(), + ) + + assertThat(roundtrippedIndividualInDirectory).isEqualTo(individualInDirectory) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualResponseTest.kt index a2663ff8..1f022127 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualResponseTest.kt @@ -2,18 +2,20 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class IndividualResponseTest { +internal class IndividualResponseTest { @Test - fun createIndividualResponse() { + fun create() { val individualResponse = IndividualResponse.builder() .body( Individual.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .dob("dob") .addEmail( Individual.Email.builder() @@ -52,11 +54,11 @@ class IndividualResponseTest { .code(0L) .individualId("individual_id") .build() - assertThat(individualResponse).isNotNull + assertThat(individualResponse.body()) .contains( Individual.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .dob("dob") .addEmail( Individual.Email.builder() @@ -95,4 +97,60 @@ class IndividualResponseTest { assertThat(individualResponse.code()).contains(0L) assertThat(individualResponse.individualId()).contains("individual_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val individualResponse = + IndividualResponse.builder() + .body( + Individual.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .dob("dob") + .addEmail( + Individual.Email.builder() + .data("data") + .type(Individual.Email.Type.WORK) + .build() + ) + .encryptedSsn("encrypted_ssn") + .ethnicity(Individual.Ethnicity.ASIAN) + .firstName("first_name") + .gender(Individual.Gender.FEMALE) + .lastName("last_name") + .middleName("middle_name") + .addPhoneNumber( + Individual.PhoneNumber.builder() + .data("data") + .type(Individual.PhoneNumber.Type.WORK) + .build() + ) + .preferredName("preferred_name") + .residence( + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() + ) + .ssn("ssn") + .build() + ) + .code(0L) + .individualId("individual_id") + .build() + + val roundtrippedIndividualResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(individualResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedIndividualResponse).isEqualTo(individualResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualTest.kt index 80107aeb..e8760c8f 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualTest.kt @@ -2,16 +2,19 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class IndividualTest { +internal class IndividualTest { @Test - fun createIndividual() { + fun create() { val individual = Individual.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .dob("dob") .addEmail( Individual.Email.builder().data("data").type(Individual.Email.Type.WORK).build() @@ -43,10 +46,10 @@ class IndividualTest { ) .ssn("ssn") .build() - assertThat(individual).isNotNull - assertThat(individual.id()).contains("id") + + assertThat(individual.id()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(individual.dob()).contains("dob") - assertThat(individual.emails().get()) + assertThat(individual.emails().getOrNull()) .containsExactly( Individual.Email.builder().data("data").type(Individual.Email.Type.WORK).build() ) @@ -56,7 +59,7 @@ class IndividualTest { assertThat(individual.gender()).contains(Individual.Gender.FEMALE) assertThat(individual.lastName()).contains("last_name") assertThat(individual.middleName()).contains("middle_name") - assertThat(individual.phoneNumbers().get()) + assertThat(individual.phoneNumbers().getOrNull()) .containsExactly( Individual.PhoneNumber.builder() .data("data") @@ -79,4 +82,51 @@ class IndividualTest { ) assertThat(individual.ssn()).contains("ssn") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val individual = + Individual.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .dob("dob") + .addEmail( + Individual.Email.builder().data("data").type(Individual.Email.Type.WORK).build() + ) + .encryptedSsn("encrypted_ssn") + .ethnicity(Individual.Ethnicity.ASIAN) + .firstName("first_name") + .gender(Individual.Gender.FEMALE) + .lastName("last_name") + .middleName("middle_name") + .addPhoneNumber( + Individual.PhoneNumber.builder() + .data("data") + .type(Individual.PhoneNumber.Type.WORK) + .build() + ) + .preferredName("preferred_name") + .residence( + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() + ) + .ssn("ssn") + .build() + + val roundtrippedIndividual = + jsonMapper.readValue( + jsonMapper.writeValueAsString(individual), + jacksonTypeRef(), + ) + + assertThat(roundtrippedIndividual).isEqualTo(individual) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualUpdateResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualUpdateResponseTest.kt index 20525b44..d61dcf48 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualUpdateResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IndividualUpdateResponseTest.kt @@ -2,16 +2,19 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class IndividualUpdateResponseTest { +internal class IndividualUpdateResponseTest { @Test - fun createIndividualUpdateResponse() { + fun create() { val individualUpdateResponse = IndividualUpdateResponse.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .dob("dob") .addEmail( IndividualUpdateResponse.Email.builder() @@ -46,10 +49,10 @@ class IndividualUpdateResponseTest { ) .ssn("ssn") .build() - assertThat(individualUpdateResponse).isNotNull - assertThat(individualUpdateResponse.id()).contains("id") + + assertThat(individualUpdateResponse.id()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(individualUpdateResponse.dob()).contains("dob") - assertThat(individualUpdateResponse.emails().get()) + assertThat(individualUpdateResponse.emails().getOrNull()) .containsExactly( IndividualUpdateResponse.Email.builder() .data("data") @@ -64,7 +67,7 @@ class IndividualUpdateResponseTest { .contains(IndividualUpdateResponse.Gender.FEMALE) assertThat(individualUpdateResponse.lastName()).contains("last_name") assertThat(individualUpdateResponse.middleName()).contains("middle_name") - assertThat(individualUpdateResponse.phoneNumbers().get()) + assertThat(individualUpdateResponse.phoneNumbers().getOrNull()) .containsExactly( IndividualUpdateResponse.PhoneNumber.builder() .data("data") @@ -87,4 +90,54 @@ class IndividualUpdateResponseTest { ) assertThat(individualUpdateResponse.ssn()).contains("ssn") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val individualUpdateResponse = + IndividualUpdateResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .dob("dob") + .addEmail( + IndividualUpdateResponse.Email.builder() + .data("data") + .type(IndividualUpdateResponse.Email.Type.WORK) + .build() + ) + .encryptedSsn("encrypted_ssn") + .ethnicity(IndividualUpdateResponse.Ethnicity.ASIAN) + .firstName("first_name") + .gender(IndividualUpdateResponse.Gender.FEMALE) + .lastName("last_name") + .middleName("middle_name") + .addPhoneNumber( + IndividualUpdateResponse.PhoneNumber.builder() + .data("data") + .type(IndividualUpdateResponse.PhoneNumber.Type.WORK) + .build() + ) + .preferredName("preferred_name") + .residence( + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() + ) + .ssn("ssn") + .build() + + val roundtrippedIndividualUpdateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(individualUpdateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedIndividualUpdateResponse).isEqualTo(individualUpdateResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IntrospectionTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IntrospectionTest.kt index 573f19a4..6b07ebce 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IntrospectionTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/IntrospectionTest.kt @@ -2,13 +2,16 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class IntrospectionTest { +internal class IntrospectionTest { @Test - fun createIntrospection() { + fun create() { val introspection = Introspection.builder() .accountId("account_id") @@ -30,6 +33,7 @@ class IntrospectionTest { .connectionId("connection_id") .connectionStatus( Introspection.ConnectionStatus.builder() + .lastSuccessfulSync(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .message("message") .status(ConnectionStatusType.PENDING) .build() @@ -44,7 +48,7 @@ class IntrospectionTest { .providerId("provider_id") .username("username") .build() - assertThat(introspection).isNotNull + assertThat(introspection.accountId()).isEqualTo("account_id") assertThat(introspection.authenticationMethods()) .containsExactly( @@ -66,6 +70,7 @@ class IntrospectionTest { assertThat(introspection.connectionStatus()) .isEqualTo( Introspection.ConnectionStatus.builder() + .lastSuccessfulSync(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .message("message") .status(ConnectionStatusType.PENDING) .build() @@ -80,4 +85,53 @@ class IntrospectionTest { assertThat(introspection.providerId()).isEqualTo("provider_id") assertThat(introspection.username()).isEqualTo("username") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val introspection = + Introspection.builder() + .accountId("account_id") + .addAuthenticationMethod( + Introspection.AuthenticationMethod.builder() + .connectionStatus( + Introspection.AuthenticationMethod.ConnectionStatus.builder() + .message("message") + .status(ConnectionStatusType.PENDING) + .build() + ) + .addProduct("string") + .type(Introspection.AuthenticationMethod.Type.ASSISTED) + .build() + ) + .clientId("client_id") + .clientType(Introspection.ClientType.PRODUCTION) + .companyId("company_id") + .connectionId("connection_id") + .connectionStatus( + Introspection.ConnectionStatus.builder() + .lastSuccessfulSync(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .message("message") + .status(ConnectionStatusType.PENDING) + .build() + ) + .connectionType(Introspection.ConnectionType.PROVIDER) + .customerEmail("customer_email") + .customerId("customer_id") + .customerName("customer_name") + .manual(true) + .payrollProviderId("payroll_provider_id") + .addProduct("string") + .providerId("provider_id") + .username("username") + .build() + + val roundtrippedIntrospection = + jsonMapper.readValue( + jsonMapper.writeValueAsString(introspection), + jacksonTypeRef(), + ) + + assertThat(roundtrippedIntrospection).isEqualTo(introspection) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobAutomatedCreateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobAutomatedCreateParamsTest.kt index 3e50cc29..8221c7e1 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobAutomatedCreateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobAutomatedCreateParamsTest.kt @@ -6,7 +6,7 @@ import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class JobAutomatedCreateParamsTest { +internal class JobAutomatedCreateParamsTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobAutomatedListParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobAutomatedListParamsTest.kt index 7d8eb4e6..a6a42d5d 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobAutomatedListParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobAutomatedListParamsTest.kt @@ -6,7 +6,7 @@ import com.tryfinch.api.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class JobAutomatedListParamsTest { +internal class JobAutomatedListParamsTest { @Test fun create() { @@ -16,16 +16,19 @@ class JobAutomatedListParamsTest { @Test fun queryParams() { val params = JobAutomatedListParams.builder().limit(0L).offset(0L).build() - val expected = QueryParams.builder() - expected.put("limit", "0") - expected.put("offset", "0") - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo(QueryParams.builder().put("limit", "0").put("offset", "0").build()) } @Test fun queryParamsWithoutOptionalFields() { val params = JobAutomatedListParams.builder().build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobAutomatedRetrieveParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobAutomatedRetrieveParamsTest.kt index 3aaceca0..d8c03a77 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobAutomatedRetrieveParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobAutomatedRetrieveParamsTest.kt @@ -5,7 +5,7 @@ package com.tryfinch.api.models import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class JobAutomatedRetrieveParamsTest { +internal class JobAutomatedRetrieveParamsTest { @Test fun create() { @@ -13,12 +13,11 @@ class JobAutomatedRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = JobAutomatedRetrieveParams.builder().jobId("job_id").build() - assertThat(params).isNotNull - // path param "jobId" - assertThat(params.getPathParam(0)).isEqualTo("job_id") + + assertThat(params._pathParam(0)).isEqualTo("job_id") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobCompletionEventTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobCompletionEventTest.kt new file mode 100644 index 00000000..0e56ec09 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobCompletionEventTest.kt @@ -0,0 +1,52 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class JobCompletionEventTest { + + @Test + fun create() { + val jobCompletionEvent = + JobCompletionEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(JobCompletionEvent.Data.builder().jobId("job_id").jobUrl("job_url").build()) + .eventType(JobCompletionEvent.EventType.JOB_BENEFIT_CREATE_COMPLETED) + .build() + + assertThat(jobCompletionEvent.accountId()).isEqualTo("account_id") + assertThat(jobCompletionEvent.companyId()).isEqualTo("company_id") + assertThat(jobCompletionEvent.connectionId()).contains("connection_id") + assertThat(jobCompletionEvent.data()) + .contains(JobCompletionEvent.Data.builder().jobId("job_id").jobUrl("job_url").build()) + assertThat(jobCompletionEvent.eventType()) + .contains(JobCompletionEvent.EventType.JOB_BENEFIT_CREATE_COMPLETED) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val jobCompletionEvent = + JobCompletionEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(JobCompletionEvent.Data.builder().jobId("job_id").jobUrl("job_url").build()) + .eventType(JobCompletionEvent.EventType.JOB_BENEFIT_CREATE_COMPLETED) + .build() + + val roundtrippedJobCompletionEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(jobCompletionEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedJobCompletionEvent).isEqualTo(jobCompletionEvent) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobCreateResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobCreateResponseTest.kt index 330d1b6a..c9a4e7d8 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobCreateResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobCreateResponseTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class JobCreateResponseTest { +internal class JobCreateResponseTest { @Test - fun createJobCreateResponse() { + fun create() { val jobCreateResponse = JobCreateResponse.builder() .allowedRefreshes(0L) @@ -16,10 +18,30 @@ class JobCreateResponseTest { .jobUrl("job_url") .remainingRefreshes(0L) .build() - assertThat(jobCreateResponse).isNotNull + assertThat(jobCreateResponse.allowedRefreshes()).isEqualTo(0L) assertThat(jobCreateResponse.jobId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(jobCreateResponse.jobUrl()).isEqualTo("job_url") assertThat(jobCreateResponse.remainingRefreshes()).isEqualTo(0L) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val jobCreateResponse = + JobCreateResponse.builder() + .allowedRefreshes(0L) + .jobId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .jobUrl("job_url") + .remainingRefreshes(0L) + .build() + + val roundtrippedJobCreateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(jobCreateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedJobCreateResponse).isEqualTo(jobCreateResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobManualRetrieveParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobManualRetrieveParamsTest.kt index 9ae5ed32..4d7590ce 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobManualRetrieveParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/JobManualRetrieveParamsTest.kt @@ -5,7 +5,7 @@ package com.tryfinch.api.models import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class JobManualRetrieveParamsTest { +internal class JobManualRetrieveParamsTest { @Test fun create() { @@ -13,12 +13,11 @@ class JobManualRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = JobManualRetrieveParams.builder().jobId("job_id").build() - assertThat(params).isNotNull - // path param "jobId" - assertThat(params.getPathParam(0)).isEqualTo("job_id") + + assertThat(params._pathParam(0)).isEqualTo("job_id") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/LocationTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/LocationTest.kt index 82a65fd0..8dc6ed3d 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/LocationTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/LocationTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class LocationTest { +internal class LocationTest { @Test - fun createLocation() { + fun create() { val location = Location.builder() .city("city") @@ -20,7 +22,7 @@ class LocationTest { .sourceId("source_id") .state("state") .build() - assertThat(location).isNotNull + assertThat(location.city()).contains("city") assertThat(location.country()).contains("country") assertThat(location.line1()).contains("line1") @@ -30,4 +32,28 @@ class LocationTest { assertThat(location.sourceId()).contains("source_id") assertThat(location.state()).contains("state") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val location = + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() + + val roundtrippedLocation = + jsonMapper.readValue( + jsonMapper.writeValueAsString(location), + jacksonTypeRef(), + ) + + assertThat(roundtrippedLocation).isEqualTo(location) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ManualAsyncJobTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ManualAsyncJobTest.kt index 198d409a..fa288270 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ManualAsyncJobTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ManualAsyncJobTest.kt @@ -2,24 +2,46 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ManualAsyncJobTest { +internal class ManualAsyncJobTest { @Test - fun createManualAsyncJob() { + fun create() { val manualAsyncJob = ManualAsyncJob.builder() .addBody(JsonValue.from(mapOf())) .jobId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .status(ManualAsyncJob.Status.PENDING) .build() - assertThat(manualAsyncJob).isNotNull - assertThat(manualAsyncJob.body().get()) + + assertThat(manualAsyncJob.body().getOrNull()) .containsExactly(JsonValue.from(mapOf())) assertThat(manualAsyncJob.jobId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(manualAsyncJob.status()).isEqualTo(ManualAsyncJob.Status.PENDING) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val manualAsyncJob = + ManualAsyncJob.builder() + .addBody(JsonValue.from(mapOf())) + .jobId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .status(ManualAsyncJob.Status.PENDING) + .build() + + val roundtrippedManualAsyncJob = + jsonMapper.readValue( + jsonMapper.writeValueAsString(manualAsyncJob), + jacksonTypeRef(), + ) + + assertThat(roundtrippedManualAsyncJob).isEqualTo(manualAsyncJob) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/MoneyTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/MoneyTest.kt index 3d0dd64a..76045e09 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/MoneyTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/MoneyTest.kt @@ -2,16 +2,29 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class MoneyTest { +internal class MoneyTest { @Test - fun createMoney() { + fun create() { val money = Money.builder().amount(0L).currency("currency").build() - assertThat(money).isNotNull + assertThat(money.amount()).contains(0L) assertThat(money.currency()).contains("currency") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val money = Money.builder().amount(0L).currency("currency").build() + + val roundtrippedMoney = + jsonMapper.readValue(jsonMapper.writeValueAsString(money), jacksonTypeRef()) + + assertThat(roundtrippedMoney).isEqualTo(money) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/OperationSupportMatrixTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/OperationSupportMatrixTest.kt index c907621d..72b1c48c 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/OperationSupportMatrixTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/OperationSupportMatrixTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class OperationSupportMatrixTest { +internal class OperationSupportMatrixTest { @Test - fun createOperationSupportMatrix() { + fun create() { val operationSupportMatrix = OperationSupportMatrix.builder() .create(OperationSupport.SUPPORTED) @@ -16,10 +18,30 @@ class OperationSupportMatrixTest { .read(OperationSupport.SUPPORTED) .update(OperationSupport.SUPPORTED) .build() - assertThat(operationSupportMatrix).isNotNull + assertThat(operationSupportMatrix.create()).contains(OperationSupport.SUPPORTED) assertThat(operationSupportMatrix.delete()).contains(OperationSupport.SUPPORTED) assertThat(operationSupportMatrix.read()).contains(OperationSupport.SUPPORTED) assertThat(operationSupportMatrix.update()).contains(OperationSupport.SUPPORTED) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val operationSupportMatrix = + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + + val roundtrippedOperationSupportMatrix = + jsonMapper.readValue( + jsonMapper.writeValueAsString(operationSupportMatrix), + jacksonTypeRef(), + ) + + assertThat(roundtrippedOperationSupportMatrix).isEqualTo(operationSupportMatrix) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PagingTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PagingTest.kt index 896698f3..0e455120 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PagingTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PagingTest.kt @@ -2,16 +2,29 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class PagingTest { +internal class PagingTest { @Test - fun createPaging() { + fun create() { val paging = Paging.builder().count(0L).offset(0L).build() - assertThat(paging).isNotNull + assertThat(paging.count()).contains(0L) assertThat(paging.offset()).contains(0L) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val paging = Paging.builder().count(0L).offset(0L).build() + + val roundtrippedPaging = + jsonMapper.readValue(jsonMapper.writeValueAsString(paging), jacksonTypeRef()) + + assertThat(roundtrippedPaging).isEqualTo(paging) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayGroupListResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayGroupListResponseTest.kt index f3c2561b..e696a7ea 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayGroupListResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayGroupListResponseTest.kt @@ -2,23 +2,45 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class PayGroupListResponseTest { +internal class PayGroupListResponseTest { @Test - fun createPayGroupListResponse() { + fun create() { val payGroupListResponse = PayGroupListResponse.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .name("name") .addPayFrequency(PayGroupListResponse.PayFrequency.ANNUALLY) .build() - assertThat(payGroupListResponse).isNotNull - assertThat(payGroupListResponse.id()).contains("id") + + assertThat(payGroupListResponse.id()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(payGroupListResponse.name()).contains("name") - assertThat(payGroupListResponse.payFrequencies().get()) + assertThat(payGroupListResponse.payFrequencies().getOrNull()) .containsExactly(PayGroupListResponse.PayFrequency.ANNUALLY) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val payGroupListResponse = + PayGroupListResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .addPayFrequency(PayGroupListResponse.PayFrequency.ANNUALLY) + .build() + + val roundtrippedPayGroupListResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(payGroupListResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedPayGroupListResponse).isEqualTo(payGroupListResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayGroupRetrieveResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayGroupRetrieveResponseTest.kt index 21f2f7c9..3fd11865 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayGroupRetrieveResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayGroupRetrieveResponseTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class PayGroupRetrieveResponseTest { +internal class PayGroupRetrieveResponseTest { @Test - fun createPayGroupRetrieveResponse() { + fun create() { val payGroupRetrieveResponse = PayGroupRetrieveResponse.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -16,7 +18,7 @@ class PayGroupRetrieveResponseTest { .name("name") .addPayFrequency(PayGroupRetrieveResponse.PayFrequency.ANNUALLY) .build() - assertThat(payGroupRetrieveResponse).isNotNull + assertThat(payGroupRetrieveResponse.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(payGroupRetrieveResponse.individualIds()) .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -24,4 +26,24 @@ class PayGroupRetrieveResponseTest { assertThat(payGroupRetrieveResponse.payFrequencies()) .containsExactly(PayGroupRetrieveResponse.PayFrequency.ANNUALLY) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val payGroupRetrieveResponse = + PayGroupRetrieveResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addIndividualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .addPayFrequency(PayGroupRetrieveResponse.PayFrequency.ANNUALLY) + .build() + + val roundtrippedPayGroupRetrieveResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(payGroupRetrieveResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedPayGroupRetrieveResponse).isEqualTo(payGroupRetrieveResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementEventTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementEventTest.kt new file mode 100644 index 00000000..126bc319 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementEventTest.kt @@ -0,0 +1,67 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PayStatementEventTest { + + @Test + fun create() { + val payStatementEvent = + PayStatementEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + PayStatementEvent.Data.builder() + .individualId("individual_id") + .paymentId("payment_id") + .build() + ) + .eventType(PayStatementEvent.EventType.PAY_STATEMENT_CREATED) + .build() + + assertThat(payStatementEvent.accountId()).isEqualTo("account_id") + assertThat(payStatementEvent.companyId()).isEqualTo("company_id") + assertThat(payStatementEvent.connectionId()).contains("connection_id") + assertThat(payStatementEvent.data()) + .contains( + PayStatementEvent.Data.builder() + .individualId("individual_id") + .paymentId("payment_id") + .build() + ) + assertThat(payStatementEvent.eventType()) + .contains(PayStatementEvent.EventType.PAY_STATEMENT_CREATED) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val payStatementEvent = + PayStatementEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + PayStatementEvent.Data.builder() + .individualId("individual_id") + .paymentId("payment_id") + .build() + ) + .eventType(PayStatementEvent.EventType.PAY_STATEMENT_CREATED) + .build() + + val roundtrippedPayStatementEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(payStatementEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedPayStatementEvent).isEqualTo(payStatementEvent) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementItemListResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementItemListResponseTest.kt new file mode 100644 index 00000000..060f17e7 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementItemListResponseTest.kt @@ -0,0 +1,68 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PayStatementItemListResponseTest { + + @Test + fun create() { + val payStatementItemListResponse = + PayStatementItemListResponse.builder() + .attributes( + PayStatementItemListResponse.Attributes.builder() + .employer(true) + .metadata(JsonValue.from(mapOf())) + .preTax(true) + .type("type") + .build() + ) + .category(PayStatementItemListResponse.Category.EARNINGS) + .name("name") + .build() + + assertThat(payStatementItemListResponse.attributes()) + .contains( + PayStatementItemListResponse.Attributes.builder() + .employer(true) + .metadata(JsonValue.from(mapOf())) + .preTax(true) + .type("type") + .build() + ) + assertThat(payStatementItemListResponse.category()) + .contains(PayStatementItemListResponse.Category.EARNINGS) + assertThat(payStatementItemListResponse.name()).contains("name") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val payStatementItemListResponse = + PayStatementItemListResponse.builder() + .attributes( + PayStatementItemListResponse.Attributes.builder() + .employer(true) + .metadata(JsonValue.from(mapOf())) + .preTax(true) + .type("type") + .build() + ) + .category(PayStatementItemListResponse.Category.EARNINGS) + .name("name") + .build() + + val roundtrippedPayStatementItemListResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(payStatementItemListResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedPayStatementItemListResponse).isEqualTo(payStatementItemListResponse) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementResponseBodyTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementResponseBodyTest.kt index 8c004da4..1d1cb6f1 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementResponseBodyTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementResponseBodyTest.kt @@ -2,14 +2,17 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class PayStatementResponseBodyTest { +internal class PayStatementResponseBodyTest { @Test - fun createPayStatementResponseBody() { + fun create() { val payStatementResponseBody = PayStatementResponseBody.builder() .paging(Paging.builder().count(0L).offset(0L).build()) @@ -135,10 +138,10 @@ class PayStatementResponseBodyTest { .build() ) .build() - assertThat(payStatementResponseBody).isNotNull + assertThat(payStatementResponseBody.paging()) .contains(Paging.builder().count(0L).offset(0L).build()) - assertThat(payStatementResponseBody.payStatements().get()) + assertThat(payStatementResponseBody.payStatements().getOrNull()) .containsExactly( PayStatement.builder() .addEarning( @@ -258,4 +261,142 @@ class PayStatementResponseBodyTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val payStatementResponseBody = + PayStatementResponseBody.builder() + .paging(Paging.builder().count(0L).offset(0L).build()) + .addPayStatement( + PayStatement.builder() + .addEarning( + PayStatement.Earning.builder() + .amount(0L) + .attributes( + PayStatement.Earning.Attributes.builder() + .metadata( + PayStatement.Earning.Attributes.Metadata.builder() + .metadata( + PayStatement.Earning.Attributes.Metadata + .InnerMetadata + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .hours(0.0) + .name("name") + .type(PayStatement.Earning.Type.SALARY) + .build() + ) + .addEmployeeDeduction( + PayStatement.EmployeeDeduction.builder() + .amount(0L) + .attributes( + PayStatement.EmployeeDeduction.Attributes.builder() + .metadata( + PayStatement.EmployeeDeduction.Attributes.Metadata + .builder() + .metadata( + PayStatement.EmployeeDeduction.Attributes + .Metadata + .InnerMetadata + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .name("name") + .preTax(true) + .type(BenefitType._401K) + .build() + ) + .addEmployerContribution( + PayStatement.EmployerContribution.builder() + .amount(0L) + .attributes( + PayStatement.EmployerContribution.Attributes.builder() + .metadata( + PayStatement.EmployerContribution.Attributes.Metadata + .builder() + .metadata( + PayStatement.EmployerContribution.Attributes + .Metadata + .InnerMetadata + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .name("name") + .type(BenefitType._401K) + .build() + ) + .grossPay(Money.builder().amount(0L).currency("currency").build()) + .individualId("individual_id") + .netPay(Money.builder().amount(0L).currency("currency").build()) + .paymentMethod(PayStatement.PaymentMethod.CHECK) + .addTax( + PayStatement.Tax.builder() + .amount(0L) + .attributes( + PayStatement.Tax.Attributes.builder() + .metadata( + PayStatement.Tax.Attributes.Metadata.builder() + .metadata( + PayStatement.Tax.Attributes.Metadata + .InnerMetadata + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .employer(true) + .name("name") + .type(PayStatement.Tax.Type.STATE) + .build() + ) + .totalHours(0.0) + .type(PayStatement.Type.REGULAR_PAYROLL) + .build() + ) + .build() + + val roundtrippedPayStatementResponseBody = + jsonMapper.readValue( + jsonMapper.writeValueAsString(payStatementResponseBody), + jacksonTypeRef(), + ) + + assertThat(roundtrippedPayStatementResponseBody).isEqualTo(payStatementResponseBody) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementResponseTest.kt index 2400e2ca..7eaf287b 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementResponseTest.kt @@ -2,14 +2,16 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class PayStatementResponseTest { +internal class PayStatementResponseTest { @Test - fun createPayStatementResponse() { + fun create() { val payStatementResponse = PayStatementResponse.builder() .body( @@ -146,7 +148,7 @@ class PayStatementResponseTest { .code(0L) .paymentId("payment_id") .build() - assertThat(payStatementResponse).isNotNull + assertThat(payStatementResponse.body()) .contains( PayStatementResponseBody.builder() @@ -278,4 +280,153 @@ class PayStatementResponseTest { assertThat(payStatementResponse.code()).contains(0L) assertThat(payStatementResponse.paymentId()).contains("payment_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val payStatementResponse = + PayStatementResponse.builder() + .body( + PayStatementResponseBody.builder() + .paging(Paging.builder().count(0L).offset(0L).build()) + .addPayStatement( + PayStatement.builder() + .addEarning( + PayStatement.Earning.builder() + .amount(0L) + .attributes( + PayStatement.Earning.Attributes.builder() + .metadata( + PayStatement.Earning.Attributes.Metadata + .builder() + .metadata( + PayStatement.Earning.Attributes.Metadata + .InnerMetadata + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .hours(0.0) + .name("name") + .type(PayStatement.Earning.Type.SALARY) + .build() + ) + .addEmployeeDeduction( + PayStatement.EmployeeDeduction.builder() + .amount(0L) + .attributes( + PayStatement.EmployeeDeduction.Attributes.builder() + .metadata( + PayStatement.EmployeeDeduction.Attributes + .Metadata + .builder() + .metadata( + PayStatement.EmployeeDeduction + .Attributes + .Metadata + .InnerMetadata + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .name("name") + .preTax(true) + .type(BenefitType._401K) + .build() + ) + .addEmployerContribution( + PayStatement.EmployerContribution.builder() + .amount(0L) + .attributes( + PayStatement.EmployerContribution.Attributes.builder() + .metadata( + PayStatement.EmployerContribution.Attributes + .Metadata + .builder() + .metadata( + PayStatement.EmployerContribution + .Attributes + .Metadata + .InnerMetadata + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .name("name") + .type(BenefitType._401K) + .build() + ) + .grossPay(Money.builder().amount(0L).currency("currency").build()) + .individualId("individual_id") + .netPay(Money.builder().amount(0L).currency("currency").build()) + .paymentMethod(PayStatement.PaymentMethod.CHECK) + .addTax( + PayStatement.Tax.builder() + .amount(0L) + .attributes( + PayStatement.Tax.Attributes.builder() + .metadata( + PayStatement.Tax.Attributes.Metadata.builder() + .metadata( + PayStatement.Tax.Attributes.Metadata + .InnerMetadata + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .employer(true) + .name("name") + .type(PayStatement.Tax.Type.STATE) + .build() + ) + .totalHours(0.0) + .type(PayStatement.Type.REGULAR_PAYROLL) + .build() + ) + .build() + ) + .code(0L) + .paymentId("payment_id") + .build() + + val roundtrippedPayStatementResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(payStatementResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedPayStatementResponse).isEqualTo(payStatementResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementTest.kt index 62d33044..db400830 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayStatementTest.kt @@ -2,14 +2,17 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class PayStatementTest { +internal class PayStatementTest { @Test - fun createPayStatement() { + fun create() { val payStatement = PayStatement.builder() .addEarning( @@ -112,8 +115,8 @@ class PayStatementTest { .totalHours(0.0) .type(PayStatement.Type.REGULAR_PAYROLL) .build() - assertThat(payStatement).isNotNull - assertThat(payStatement.earnings().get()) + + assertThat(payStatement.earnings().getOrNull()) .containsExactly( PayStatement.Earning.builder() .amount(0L) @@ -137,7 +140,7 @@ class PayStatementTest { .type(PayStatement.Earning.Type.SALARY) .build() ) - assertThat(payStatement.employeeDeductions().get()) + assertThat(payStatement.employeeDeductions().getOrNull()) .containsExactly( PayStatement.EmployeeDeduction.builder() .amount(0L) @@ -162,7 +165,7 @@ class PayStatementTest { .type(BenefitType._401K) .build() ) - assertThat(payStatement.employerContributions().get()) + assertThat(payStatement.employerContributions().getOrNull()) .containsExactly( PayStatement.EmployerContribution.builder() .amount(0L) @@ -192,7 +195,7 @@ class PayStatementTest { assertThat(payStatement.netPay()) .contains(Money.builder().amount(0L).currency("currency").build()) assertThat(payStatement.paymentMethod()).contains(PayStatement.PaymentMethod.CHECK) - assertThat(payStatement.taxes().get()) + assertThat(payStatement.taxes().getOrNull()) .containsExactly( PayStatement.Tax.builder() .amount(0L) @@ -218,4 +221,119 @@ class PayStatementTest { assertThat(payStatement.totalHours()).contains(0.0) assertThat(payStatement.type()).contains(PayStatement.Type.REGULAR_PAYROLL) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val payStatement = + PayStatement.builder() + .addEarning( + PayStatement.Earning.builder() + .amount(0L) + .attributes( + PayStatement.Earning.Attributes.builder() + .metadata( + PayStatement.Earning.Attributes.Metadata.builder() + .metadata( + PayStatement.Earning.Attributes.Metadata.InnerMetadata + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .hours(0.0) + .name("name") + .type(PayStatement.Earning.Type.SALARY) + .build() + ) + .addEmployeeDeduction( + PayStatement.EmployeeDeduction.builder() + .amount(0L) + .attributes( + PayStatement.EmployeeDeduction.Attributes.builder() + .metadata( + PayStatement.EmployeeDeduction.Attributes.Metadata.builder() + .metadata( + PayStatement.EmployeeDeduction.Attributes.Metadata + .InnerMetadata + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .name("name") + .preTax(true) + .type(BenefitType._401K) + .build() + ) + .addEmployerContribution( + PayStatement.EmployerContribution.builder() + .amount(0L) + .attributes( + PayStatement.EmployerContribution.Attributes.builder() + .metadata( + PayStatement.EmployerContribution.Attributes.Metadata.builder() + .metadata( + PayStatement.EmployerContribution.Attributes.Metadata + .InnerMetadata + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .name("name") + .type(BenefitType._401K) + .build() + ) + .grossPay(Money.builder().amount(0L).currency("currency").build()) + .individualId("individual_id") + .netPay(Money.builder().amount(0L).currency("currency").build()) + .paymentMethod(PayStatement.PaymentMethod.CHECK) + .addTax( + PayStatement.Tax.builder() + .amount(0L) + .attributes( + PayStatement.Tax.Attributes.builder() + .metadata( + PayStatement.Tax.Attributes.Metadata.builder() + .metadata( + PayStatement.Tax.Attributes.Metadata.InnerMetadata + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .employer(true) + .name("name") + .type(PayStatement.Tax.Type.STATE) + .build() + ) + .totalHours(0.0) + .type(PayStatement.Type.REGULAR_PAYROLL) + .build() + + val roundtrippedPayStatement = + jsonMapper.readValue( + jsonMapper.writeValueAsString(payStatement), + jacksonTypeRef(), + ) + + assertThat(roundtrippedPayStatement).isEqualTo(payStatement) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PaymentCreateResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PaymentCreateResponseTest.kt index 16d8a746..3b83aabc 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PaymentCreateResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PaymentCreateResponseTest.kt @@ -2,17 +2,34 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class PaymentCreateResponseTest { +internal class PaymentCreateResponseTest { @Test - fun createPaymentCreateResponse() { + fun create() { val paymentCreateResponse = PaymentCreateResponse.builder().payDate("pay_date").paymentId("payment_id").build() - assertThat(paymentCreateResponse).isNotNull + assertThat(paymentCreateResponse.payDate()).isEqualTo("pay_date") assertThat(paymentCreateResponse.paymentId()).isEqualTo("payment_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val paymentCreateResponse = + PaymentCreateResponse.builder().payDate("pay_date").paymentId("payment_id").build() + + val roundtrippedPaymentCreateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(paymentCreateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedPaymentCreateResponse).isEqualTo(paymentCreateResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PaymentEventTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PaymentEventTest.kt new file mode 100644 index 00000000..f118ea2f --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PaymentEventTest.kt @@ -0,0 +1,66 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PaymentEventTest { + + @Test + fun create() { + val paymentEvent = + PaymentEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + PaymentEvent.PaymentIdentifiers.builder() + .payDate("pay_date") + .paymentId("payment_id") + .build() + ) + .eventType(PaymentEvent.EventType.PAYMENT_CREATED) + .build() + + assertThat(paymentEvent.accountId()).isEqualTo("account_id") + assertThat(paymentEvent.companyId()).isEqualTo("company_id") + assertThat(paymentEvent.connectionId()).contains("connection_id") + assertThat(paymentEvent.data()) + .contains( + PaymentEvent.PaymentIdentifiers.builder() + .payDate("pay_date") + .paymentId("payment_id") + .build() + ) + assertThat(paymentEvent.eventType()).contains(PaymentEvent.EventType.PAYMENT_CREATED) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val paymentEvent = + PaymentEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + PaymentEvent.PaymentIdentifiers.builder() + .payDate("pay_date") + .paymentId("payment_id") + .build() + ) + .eventType(PaymentEvent.EventType.PAYMENT_CREATED) + .build() + + val roundtrippedPaymentEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(paymentEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedPaymentEvent).isEqualTo(paymentEvent) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PaymentTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PaymentTest.kt index 42235e2a..fce8572b 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PaymentTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PaymentTest.kt @@ -2,32 +2,35 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class PaymentTest { +internal class PaymentTest { @Test - fun createPayment() { + fun create() { val payment = Payment.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .companyDebit(Money.builder().amount(0L).currency("currency").build()) .debitDate("debit_date") .employeeTaxes(Money.builder().amount(0L).currency("currency").build()) .employerTaxes(Money.builder().amount(0L).currency("currency").build()) .grossPay(Money.builder().amount(0L).currency("currency").build()) - .addIndividualId("string") + .addIndividualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .netPay(Money.builder().amount(0L).currency("currency").build()) .payDate("pay_date") .addPayFrequency(Payment.PayFrequency.ANNUALLY) - .addPayGroupId("string") + .addPayGroupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .payPeriod( Payment.PayPeriod.builder().endDate("end_date").startDate("start_date").build() ) .build() - assertThat(payment).isNotNull - assertThat(payment.id()).contains("id") + + assertThat(payment.id()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(payment.companyDebit()) .contains(Money.builder().amount(0L).currency("currency").build()) assertThat(payment.debitDate()).contains("debit_date") @@ -37,15 +40,45 @@ class PaymentTest { .contains(Money.builder().amount(0L).currency("currency").build()) assertThat(payment.grossPay()) .contains(Money.builder().amount(0L).currency("currency").build()) - assertThat(payment.individualIds().get()).containsExactly("string") + assertThat(payment.individualIds().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(payment.netPay()) .contains(Money.builder().amount(0L).currency("currency").build()) assertThat(payment.payDate()).contains("pay_date") - assertThat(payment.payFrequencies().get()).containsExactly(Payment.PayFrequency.ANNUALLY) - assertThat(payment.payGroupIds().get()).containsExactly("string") + assertThat(payment.payFrequencies().getOrNull()) + .containsExactly(Payment.PayFrequency.ANNUALLY) + assertThat(payment.payGroupIds().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(payment.payPeriod()) .contains( Payment.PayPeriod.builder().endDate("end_date").startDate("start_date").build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val payment = + Payment.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .companyDebit(Money.builder().amount(0L).currency("currency").build()) + .debitDate("debit_date") + .employeeTaxes(Money.builder().amount(0L).currency("currency").build()) + .employerTaxes(Money.builder().amount(0L).currency("currency").build()) + .grossPay(Money.builder().amount(0L).currency("currency").build()) + .addIndividualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .netPay(Money.builder().amount(0L).currency("currency").build()) + .payDate("pay_date") + .addPayFrequency(Payment.PayFrequency.ANNUALLY) + .addPayGroupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .payPeriod( + Payment.PayPeriod.builder().endDate("end_date").startDate("start_date").build() + ) + .build() + + val roundtrippedPayment = + jsonMapper.readValue(jsonMapper.writeValueAsString(payment), jacksonTypeRef()) + + assertThat(roundtrippedPayment).isEqualTo(payment) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayrollPayGroupListParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayrollPayGroupListParamsTest.kt index 45029bf7..a17dc1ae 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayrollPayGroupListParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayrollPayGroupListParamsTest.kt @@ -6,7 +6,7 @@ import com.tryfinch.api.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class PayrollPayGroupListParamsTest { +internal class PayrollPayGroupListParamsTest { @Test fun create() { @@ -23,16 +23,24 @@ class PayrollPayGroupListParamsTest { .individualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .addPayFrequency("string") .build() - val expected = QueryParams.builder() - expected.put("individual_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - expected.put("pay_frequencies[]", "string") - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("individual_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("pay_frequencies[]", "string") + .build() + ) } @Test fun queryParamsWithoutOptionalFields() { val params = PayrollPayGroupListParams.builder().build() - val expected = QueryParams.builder() - assertThat(params._queryParams()).isEqualTo(expected.build()) + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayrollPayGroupRetrieveParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayrollPayGroupRetrieveParamsTest.kt index 657b7fd2..47419b7f 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayrollPayGroupRetrieveParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/PayrollPayGroupRetrieveParamsTest.kt @@ -5,7 +5,7 @@ package com.tryfinch.api.models import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class PayrollPayGroupRetrieveParamsTest { +internal class PayrollPayGroupRetrieveParamsTest { @Test fun create() { @@ -13,12 +13,11 @@ class PayrollPayGroupRetrieveParamsTest { } @Test - fun getPathParam() { + fun pathParams() { val params = PayrollPayGroupRetrieveParams.builder().payGroupId("pay_group_id").build() - assertThat(params).isNotNull - // path param "payGroupId" - assertThat(params.getPathParam(0)).isEqualTo("pay_group_id") + + assertThat(params._pathParam(0)).isEqualTo("pay_group_id") // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") + assertThat(params._pathParam(1)).isEqualTo("") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ProviderListParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ProviderListParamsTest.kt index a3b71dac..0e0c7c6f 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ProviderListParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ProviderListParamsTest.kt @@ -4,7 +4,7 @@ package com.tryfinch.api.models import org.junit.jupiter.api.Test -class ProviderListParamsTest { +internal class ProviderListParamsTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ProviderTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ProviderTest.kt index e16e32ae..c8c8d6be 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ProviderTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/ProviderTest.kt @@ -2,13 +2,16 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ProviderTest { +internal class ProviderTest { @Test - fun createProvider() { + fun create() { val provider = Provider.builder() .id("id") @@ -923,9 +926,9 @@ class ProviderTest { .primaryColor("primary_color") .addProduct("string") .build() - assertThat(provider).isNotNull + assertThat(provider.id()).contains("id") - assertThat(provider.authenticationMethods().get()) + assertThat(provider.authenticationMethods().getOrNull()) .containsExactly( Provider.AuthenticationMethod.builder() .benefitsSupport( @@ -1833,6 +1836,933 @@ class ProviderTest { assertThat(provider.manual()).contains(true) assertThat(provider.mfaRequired()).contains(true) assertThat(provider.primaryColor()).contains("primary_color") - assertThat(provider.products().get()).containsExactly("string") + assertThat(provider.products().getOrNull()).containsExactly("string") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val provider = + Provider.builder() + .id("id") + .addAuthenticationMethod( + Provider.AuthenticationMethod.builder() + .benefitsSupport( + BenefitsSupport.builder() + .commuter( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .customPostTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .customPreTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .fsaDependentCare( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .fsaMedical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .hsaPost( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .hsaPre( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Dental( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Medical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Vision( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .simple( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .simpleIra( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations.BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations.BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations.BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .build() + ) + .supportedFields( + Provider.AuthenticationMethod.SupportedFields.builder() + .company( + Provider.AuthenticationMethod.SupportedFields + .SupportedCompanyFields + .builder() + .id(true) + .accounts( + Provider.AuthenticationMethod.SupportedFields + .SupportedCompanyFields + .Accounts + .builder() + .accountName(true) + .accountNumber(true) + .accountType(true) + .institutionName(true) + .routingNumber(true) + .build() + ) + .departments( + Provider.AuthenticationMethod.SupportedFields + .SupportedCompanyFields + .Departments + .builder() + .name(true) + .parent( + Provider.AuthenticationMethod.SupportedFields + .SupportedCompanyFields + .Departments + .Parent + .builder() + .name(true) + .build() + ) + .build() + ) + .ein(true) + .entity( + Provider.AuthenticationMethod.SupportedFields + .SupportedCompanyFields + .Entity + .builder() + .subtype(true) + .type(true) + .build() + ) + .legalName(true) + .locations( + Provider.AuthenticationMethod.SupportedFields + .SupportedCompanyFields + .Locations + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .primaryEmail(true) + .primaryPhoneNumber(true) + .build() + ) + .directory( + Provider.AuthenticationMethod.SupportedFields + .SupportedDirectoryFields + .builder() + .individuals( + Provider.AuthenticationMethod.SupportedFields + .SupportedDirectoryFields + .Individuals + .builder() + .id(true) + .department(true) + .firstName(true) + .isActive(true) + .lastName(true) + .manager( + Provider.AuthenticationMethod.SupportedFields + .SupportedDirectoryFields + .Individuals + .Manager + .builder() + .id(true) + .build() + ) + .middleName(true) + .build() + ) + .paging( + Provider.AuthenticationMethod.SupportedFields + .SupportedDirectoryFields + .Paging + .builder() + .count(true) + .offset(true) + .build() + ) + .build() + ) + .employment( + Provider.AuthenticationMethod.SupportedFields + .SupportedEmploymentFields + .builder() + .id(true) + .classCode(true) + .customFields(true) + .department( + Provider.AuthenticationMethod.SupportedFields + .SupportedEmploymentFields + .Department + .builder() + .name(true) + .build() + ) + .employment( + Provider.AuthenticationMethod.SupportedFields + .SupportedEmploymentFields + .Employment + .builder() + .subtype(true) + .type(true) + .build() + ) + .employmentStatus(true) + .endDate(true) + .firstName(true) + .income( + Provider.AuthenticationMethod.SupportedFields + .SupportedEmploymentFields + .Income + .builder() + .amount(true) + .currency(true) + .unit(true) + .build() + ) + .incomeHistory(true) + .isActive(true) + .lastName(true) + .location( + Provider.AuthenticationMethod.SupportedFields + .SupportedEmploymentFields + .Location + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .manager( + Provider.AuthenticationMethod.SupportedFields + .SupportedEmploymentFields + .Manager + .builder() + .id(true) + .build() + ) + .middleName(true) + .startDate(true) + .title(true) + .build() + ) + .individual( + Provider.AuthenticationMethod.SupportedFields + .SupportedIndividualFields + .builder() + .id(true) + .dob(true) + .emails( + Provider.AuthenticationMethod.SupportedFields + .SupportedIndividualFields + .Emails + .builder() + .data(true) + .type(true) + .build() + ) + .encryptedSsn(true) + .ethnicity(true) + .firstName(true) + .gender(true) + .lastName(true) + .middleName(true) + .phoneNumbers( + Provider.AuthenticationMethod.SupportedFields + .SupportedIndividualFields + .PhoneNumbers + .builder() + .data(true) + .type(true) + .build() + ) + .preferredName(true) + .residence( + Provider.AuthenticationMethod.SupportedFields + .SupportedIndividualFields + .Residence + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .ssn(true) + .build() + ) + .payGroup( + Provider.AuthenticationMethod.SupportedFields + .SupportedPayGroupFields + .builder() + .id(true) + .individualIds(true) + .name(true) + .payFrequencies(true) + .build() + ) + .payStatement( + Provider.AuthenticationMethod.SupportedFields + .SupportedPayStatementFields + .builder() + .paging( + Provider.AuthenticationMethod.SupportedFields + .SupportedPayStatementFields + .Paging + .builder() + .count(true) + .offset(true) + .build() + ) + .payStatements( + Provider.AuthenticationMethod.SupportedFields + .SupportedPayStatementFields + .PayStatements + .builder() + .earnings( + Provider.AuthenticationMethod.SupportedFields + .SupportedPayStatementFields + .PayStatements + .Earnings + .builder() + .amount(true) + .currency(true) + .name(true) + .type(true) + .build() + ) + .employeeDeductions( + Provider.AuthenticationMethod.SupportedFields + .SupportedPayStatementFields + .PayStatements + .EmployeeDeductions + .builder() + .amount(true) + .currency(true) + .name(true) + .preTax(true) + .type(true) + .build() + ) + .employerContributions( + Provider.AuthenticationMethod.SupportedFields + .SupportedPayStatementFields + .PayStatements + .EmployerContributions + .builder() + .amount(true) + .currency(true) + .name(true) + .build() + ) + .grossPay(true) + .individualId(true) + .netPay(true) + .paymentMethod(true) + .taxes( + Provider.AuthenticationMethod.SupportedFields + .SupportedPayStatementFields + .PayStatements + .Taxes + .builder() + .amount(true) + .currency(true) + .employer(true) + .name(true) + .type(true) + .build() + ) + .totalHours(true) + .type(true) + .build() + ) + .build() + ) + .payment( + Provider.AuthenticationMethod.SupportedFields + .SupportedPaymentFields + .builder() + .id(true) + .companyDebit(true) + .debitDate(true) + .employeeTaxes(true) + .employerTaxes(true) + .grossPay(true) + .individualIds(true) + .netPay(true) + .payDate(true) + .payFrequencies(true) + .payGroupIds(true) + .payPeriod( + Provider.AuthenticationMethod.SupportedFields + .SupportedPaymentFields + .PayPeriod + .builder() + .endDate(true) + .startDate(true) + .build() + ) + .build() + ) + .build() + ) + .type(Provider.AuthenticationMethod.Type.ASSISTED) + .build() + ) + .beta(true) + .displayName("display_name") + .icon("icon") + .logo("logo") + .manual(true) + .mfaRequired(true) + .primaryColor("primary_color") + .addProduct("string") + .build() + + val roundtrippedProvider = + jsonMapper.readValue( + jsonMapper.writeValueAsString(provider), + jacksonTypeRef(), + ) + + assertThat(roundtrippedProvider).isEqualTo(provider) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RequestForwardingForwardParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RequestForwardingForwardParamsTest.kt index d754bf09..38808fb4 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RequestForwardingForwardParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RequestForwardingForwardParamsTest.kt @@ -3,11 +3,10 @@ package com.tryfinch.api.models import com.tryfinch.api.core.JsonValue -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class RequestForwardingForwardParamsTest { +internal class RequestForwardingForwardParamsTest { @Test fun create() { @@ -33,7 +32,6 @@ class RequestForwardingForwardParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.method()).isEqualTo("POST") assertThat(body.route()).isEqualTo("/people/search") assertThat(body.data()).isEmpty @@ -50,7 +48,6 @@ class RequestForwardingForwardParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.method()).isEqualTo("POST") assertThat(body.route()).isEqualTo("/people/search") } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RequestForwardingForwardResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RequestForwardingForwardResponseTest.kt index c08f7e8f..2645792c 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RequestForwardingForwardResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RequestForwardingForwardResponseTest.kt @@ -2,14 +2,16 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class RequestForwardingForwardResponseTest { +internal class RequestForwardingForwardResponseTest { @Test - fun createRequestForwardingForwardResponse() { + fun create() { val requestForwardingForwardResponse = RequestForwardingForwardResponse.builder() .data("data") @@ -25,7 +27,7 @@ class RequestForwardingForwardResponseTest { ) .statusCode(0L) .build() - assertThat(requestForwardingForwardResponse).isNotNull + assertThat(requestForwardingForwardResponse.data()).contains("data") assertThat(requestForwardingForwardResponse._headers()) .isEqualTo(JsonValue.from(mapOf())) @@ -41,4 +43,33 @@ class RequestForwardingForwardResponseTest { ) assertThat(requestForwardingForwardResponse.statusCode()).isEqualTo(0L) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val requestForwardingForwardResponse = + RequestForwardingForwardResponse.builder() + .data("data") + .headers(JsonValue.from(mapOf())) + .request( + RequestForwardingForwardResponse.Request.builder() + .data("data") + .headers(JsonValue.from(mapOf())) + .method("method") + .params(JsonValue.from(mapOf())) + .route("route") + .build() + ) + .statusCode(0L) + .build() + + val roundtrippedRequestForwardingForwardResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(requestForwardingForwardResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedRequestForwardingForwardResponse) + .isEqualTo(requestForwardingForwardResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RuleCreateResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RuleCreateResponseTest.kt new file mode 100644 index 00000000..dd7461a8 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RuleCreateResponseTest.kt @@ -0,0 +1,112 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper +import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class RuleCreateResponseTest { + + @Test + fun create() { + val ruleCreateResponse = + RuleCreateResponse.builder() + .id("id") + .attributes( + RuleCreateResponse.Attributes.builder() + .metadata( + RuleCreateResponse.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .addCondition( + RuleCreateResponse.Condition.builder() + .field("field") + .operator(RuleCreateResponse.Condition.Operator.EQUALS) + .value("value") + .build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .effectiveEndDate("effective_end_date") + .effectiveStartDate("effective_start_date") + .entityType(RuleCreateResponse.EntityType.PAY_STATEMENT_ITEM) + .priority(0L) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + assertThat(ruleCreateResponse.id()).contains("id") + assertThat(ruleCreateResponse.attributes()) + .contains( + RuleCreateResponse.Attributes.builder() + .metadata( + RuleCreateResponse.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + assertThat(ruleCreateResponse.conditions().getOrNull()) + .containsExactly( + RuleCreateResponse.Condition.builder() + .field("field") + .operator(RuleCreateResponse.Condition.Operator.EQUALS) + .value("value") + .build() + ) + assertThat(ruleCreateResponse.createdAt()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(ruleCreateResponse.effectiveEndDate()).contains("effective_end_date") + assertThat(ruleCreateResponse.effectiveStartDate()).contains("effective_start_date") + assertThat(ruleCreateResponse.entityType()) + .contains(RuleCreateResponse.EntityType.PAY_STATEMENT_ITEM) + assertThat(ruleCreateResponse.priority()).contains(0L) + assertThat(ruleCreateResponse.updatedAt()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val ruleCreateResponse = + RuleCreateResponse.builder() + .id("id") + .attributes( + RuleCreateResponse.Attributes.builder() + .metadata( + RuleCreateResponse.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .addCondition( + RuleCreateResponse.Condition.builder() + .field("field") + .operator(RuleCreateResponse.Condition.Operator.EQUALS) + .value("value") + .build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .effectiveEndDate("effective_end_date") + .effectiveStartDate("effective_start_date") + .entityType(RuleCreateResponse.EntityType.PAY_STATEMENT_ITEM) + .priority(0L) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + val roundtrippedRuleCreateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(ruleCreateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedRuleCreateResponse).isEqualTo(ruleCreateResponse) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RuleDeleteResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RuleDeleteResponseTest.kt new file mode 100644 index 00000000..c8bd0e40 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RuleDeleteResponseTest.kt @@ -0,0 +1,116 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper +import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class RuleDeleteResponseTest { + + @Test + fun create() { + val ruleDeleteResponse = + RuleDeleteResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .attributes( + RuleDeleteResponse.Attributes.builder() + .metadata( + RuleDeleteResponse.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .addCondition( + RuleDeleteResponse.Condition.builder() + .field("field") + .operator(RuleDeleteResponse.Condition.Operator.EQUALS) + .value("value") + .build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .effectiveEndDate("effective_end_date") + .effectiveStartDate("effective_start_date") + .entityType(RuleDeleteResponse.EntityType.PAY_STATEMENT_ITEM) + .priority(0L) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + assertThat(ruleDeleteResponse.id()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(ruleDeleteResponse.attributes()) + .contains( + RuleDeleteResponse.Attributes.builder() + .metadata( + RuleDeleteResponse.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + assertThat(ruleDeleteResponse.conditions().getOrNull()) + .containsExactly( + RuleDeleteResponse.Condition.builder() + .field("field") + .operator(RuleDeleteResponse.Condition.Operator.EQUALS) + .value("value") + .build() + ) + assertThat(ruleDeleteResponse.createdAt()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(ruleDeleteResponse.deletedAt()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(ruleDeleteResponse.effectiveEndDate()).contains("effective_end_date") + assertThat(ruleDeleteResponse.effectiveStartDate()).contains("effective_start_date") + assertThat(ruleDeleteResponse.entityType()) + .contains(RuleDeleteResponse.EntityType.PAY_STATEMENT_ITEM) + assertThat(ruleDeleteResponse.priority()).contains(0L) + assertThat(ruleDeleteResponse.updatedAt()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val ruleDeleteResponse = + RuleDeleteResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .attributes( + RuleDeleteResponse.Attributes.builder() + .metadata( + RuleDeleteResponse.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .addCondition( + RuleDeleteResponse.Condition.builder() + .field("field") + .operator(RuleDeleteResponse.Condition.Operator.EQUALS) + .value("value") + .build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .effectiveEndDate("effective_end_date") + .effectiveStartDate("effective_start_date") + .entityType(RuleDeleteResponse.EntityType.PAY_STATEMENT_ITEM) + .priority(0L) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + val roundtrippedRuleDeleteResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(ruleDeleteResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedRuleDeleteResponse).isEqualTo(ruleDeleteResponse) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RuleListResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RuleListResponseTest.kt new file mode 100644 index 00000000..0b94935a --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RuleListResponseTest.kt @@ -0,0 +1,112 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper +import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class RuleListResponseTest { + + @Test + fun create() { + val ruleListResponse = + RuleListResponse.builder() + .id("id") + .attributes( + RuleListResponse.Attributes.builder() + .metadata( + RuleListResponse.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .addCondition( + RuleListResponse.Condition.builder() + .field("field") + .operator(RuleListResponse.Condition.Operator.EQUALS) + .value("value") + .build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .effectiveEndDate("effective_end_date") + .effectiveStartDate("effective_start_date") + .entityType(RuleListResponse.EntityType.PAY_STATEMENT_ITEM) + .priority(0L) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + assertThat(ruleListResponse.id()).contains("id") + assertThat(ruleListResponse.attributes()) + .contains( + RuleListResponse.Attributes.builder() + .metadata( + RuleListResponse.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + assertThat(ruleListResponse.conditions().getOrNull()) + .containsExactly( + RuleListResponse.Condition.builder() + .field("field") + .operator(RuleListResponse.Condition.Operator.EQUALS) + .value("value") + .build() + ) + assertThat(ruleListResponse.createdAt()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(ruleListResponse.effectiveEndDate()).contains("effective_end_date") + assertThat(ruleListResponse.effectiveStartDate()).contains("effective_start_date") + assertThat(ruleListResponse.entityType()) + .contains(RuleListResponse.EntityType.PAY_STATEMENT_ITEM) + assertThat(ruleListResponse.priority()).contains(0L) + assertThat(ruleListResponse.updatedAt()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val ruleListResponse = + RuleListResponse.builder() + .id("id") + .attributes( + RuleListResponse.Attributes.builder() + .metadata( + RuleListResponse.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .addCondition( + RuleListResponse.Condition.builder() + .field("field") + .operator(RuleListResponse.Condition.Operator.EQUALS) + .value("value") + .build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .effectiveEndDate("effective_end_date") + .effectiveStartDate("effective_start_date") + .entityType(RuleListResponse.EntityType.PAY_STATEMENT_ITEM) + .priority(0L) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + val roundtrippedRuleListResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(ruleListResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedRuleListResponse).isEqualTo(ruleListResponse) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RuleUpdateResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RuleUpdateResponseTest.kt new file mode 100644 index 00000000..3594a5ce --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/RuleUpdateResponseTest.kt @@ -0,0 +1,112 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper +import java.time.OffsetDateTime +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class RuleUpdateResponseTest { + + @Test + fun create() { + val ruleUpdateResponse = + RuleUpdateResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .attributes( + RuleUpdateResponse.Attributes.builder() + .metadata( + RuleUpdateResponse.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .addCondition( + RuleUpdateResponse.Condition.builder() + .field("field") + .operator(RuleUpdateResponse.Condition.Operator.EQUALS) + .value("value") + .build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .effectiveEndDate("effective_end_date") + .effectiveStartDate("effective_start_date") + .entityType(RuleUpdateResponse.EntityType.PAY_STATEMENT_ITEM) + .priority(0L) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + assertThat(ruleUpdateResponse.id()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(ruleUpdateResponse.attributes()) + .contains( + RuleUpdateResponse.Attributes.builder() + .metadata( + RuleUpdateResponse.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + assertThat(ruleUpdateResponse.conditions().getOrNull()) + .containsExactly( + RuleUpdateResponse.Condition.builder() + .field("field") + .operator(RuleUpdateResponse.Condition.Operator.EQUALS) + .value("value") + .build() + ) + assertThat(ruleUpdateResponse.createdAt()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(ruleUpdateResponse.effectiveEndDate()).contains("effective_end_date") + assertThat(ruleUpdateResponse.effectiveStartDate()).contains("effective_start_date") + assertThat(ruleUpdateResponse.entityType()) + .contains(RuleUpdateResponse.EntityType.PAY_STATEMENT_ITEM) + assertThat(ruleUpdateResponse.priority()).contains(0L) + assertThat(ruleUpdateResponse.updatedAt()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val ruleUpdateResponse = + RuleUpdateResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .attributes( + RuleUpdateResponse.Attributes.builder() + .metadata( + RuleUpdateResponse.Attributes.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .addCondition( + RuleUpdateResponse.Condition.builder() + .field("field") + .operator(RuleUpdateResponse.Condition.Operator.EQUALS) + .value("value") + .build() + ) + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .effectiveEndDate("effective_end_date") + .effectiveStartDate("effective_start_date") + .entityType(RuleUpdateResponse.EntityType.PAY_STATEMENT_ITEM) + .priority(0L) + .updatedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + val roundtrippedRuleUpdateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(ruleUpdateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedRuleUpdateResponse).isEqualTo(ruleUpdateResponse) + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxCompanyUpdateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxCompanyUpdateParamsTest.kt index 111736a3..149dc4c6 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxCompanyUpdateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxCompanyUpdateParamsTest.kt @@ -2,11 +2,11 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SandboxCompanyUpdateParamsTest { +internal class SandboxCompanyUpdateParamsTest { @Test fun create() { @@ -48,7 +48,7 @@ class SandboxCompanyUpdateParamsTest { .state("state") .build() ) - .primaryEmail("primary_email") + .primaryEmail("dev@stainless.com") .primaryPhoneNumber("primary_phone_number") .build() } @@ -96,37 +96,30 @@ class SandboxCompanyUpdateParamsTest { .state("state") .build() ) - .primaryEmail("primary_email") + .primaryEmail("dev@stainless.com") .primaryPhoneNumber("primary_phone_number") .build() val body = params._body() - assertNotNull(body) - assertThat(body.accounts()) - .contains( - listOf( - SandboxCompanyUpdateParams.Account.builder() - .accountName("account_name") - .accountNumber("account_number") - .accountType(SandboxCompanyUpdateParams.Account.AccountType.CHECKING) - .institutionName("institution_name") - .routingNumber("routing_number") - .build() - ) + assertThat(body.accounts().getOrNull()) + .containsExactly( + SandboxCompanyUpdateParams.Account.builder() + .accountName("account_name") + .accountNumber("account_number") + .accountType(SandboxCompanyUpdateParams.Account.AccountType.CHECKING) + .institutionName("institution_name") + .routingNumber("routing_number") + .build() ) - assertThat(body.departments()) - .contains( - listOf( - SandboxCompanyUpdateParams.Department.builder() - .name("name") - .parent( - SandboxCompanyUpdateParams.Department.Parent.builder() - .name("name") - .build() - ) - .build() - ) + assertThat(body.departments().getOrNull()) + .containsExactly( + SandboxCompanyUpdateParams.Department.builder() + .name("name") + .parent( + SandboxCompanyUpdateParams.Department.Parent.builder().name("name").build() + ) + .build() ) assertThat(body.ein()).contains("ein") assertThat(body.entity()) @@ -137,22 +130,20 @@ class SandboxCompanyUpdateParamsTest { .build() ) assertThat(body.legalName()).contains("legal_name") - assertThat(body.locations()) - .contains( - listOf( - Location.builder() - .city("city") - .country("country") - .line1("line1") - .line2("line2") - .name("name") - .postalCode("postal_code") - .sourceId("source_id") - .state("state") - .build() - ) + assertThat(body.locations().getOrNull()) + .containsExactly( + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() ) - assertThat(body.primaryEmail()).contains("primary_email") + assertThat(body.primaryEmail()).contains("dev@stainless.com") assertThat(body.primaryPhoneNumber()).contains("primary_phone_number") } @@ -166,22 +157,21 @@ class SandboxCompanyUpdateParamsTest { .entity(SandboxCompanyUpdateParams.Entity.builder().build()) .legalName("legal_name") .addLocation(Location.builder().build()) - .primaryEmail("primary_email") + .primaryEmail("dev@stainless.com") .primaryPhoneNumber("primary_phone_number") .build() val body = params._body() - assertNotNull(body) - assertThat(body.accounts()) - .contains(listOf(SandboxCompanyUpdateParams.Account.builder().build())) - assertThat(body.departments()) - .contains(listOf(SandboxCompanyUpdateParams.Department.builder().build())) + assertThat(body.accounts().getOrNull()) + .containsExactly(SandboxCompanyUpdateParams.Account.builder().build()) + assertThat(body.departments().getOrNull()) + .containsExactly(SandboxCompanyUpdateParams.Department.builder().build()) assertThat(body.ein()).contains("ein") assertThat(body.entity()).contains(SandboxCompanyUpdateParams.Entity.builder().build()) assertThat(body.legalName()).contains("legal_name") - assertThat(body.locations()).contains(listOf(Location.builder().build())) - assertThat(body.primaryEmail()).contains("primary_email") + assertThat(body.locations().getOrNull()).containsExactly(Location.builder().build()) + assertThat(body.primaryEmail()).contains("dev@stainless.com") assertThat(body.primaryPhoneNumber()).contains("primary_phone_number") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxConnectionAccountCreateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxConnectionAccountCreateParamsTest.kt index 666843c0..7c96bfa4 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxConnectionAccountCreateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxConnectionAccountCreateParamsTest.kt @@ -2,11 +2,11 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SandboxConnectionAccountCreateParamsTest { +internal class SandboxConnectionAccountCreateParamsTest { @Test fun create() { @@ -32,12 +32,11 @@ class SandboxConnectionAccountCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.companyId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.providerId()).isEqualTo("provider_id") assertThat(body.authenticationType()) .contains(SandboxConnectionAccountCreateParams.AuthenticationType.CREDENTIAL) - assertThat(body.products()).contains(listOf("string")) + assertThat(body.products().getOrNull()).containsExactly("string") } @Test @@ -50,7 +49,6 @@ class SandboxConnectionAccountCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.companyId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(body.providerId()).isEqualTo("provider_id") } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxConnectionAccountUpdateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxConnectionAccountUpdateParamsTest.kt index 4a60449c..702e7b3d 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxConnectionAccountUpdateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxConnectionAccountUpdateParamsTest.kt @@ -2,16 +2,15 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SandboxConnectionAccountUpdateParamsTest { +internal class SandboxConnectionAccountUpdateParamsTest { @Test fun create() { SandboxConnectionAccountUpdateParams.builder() - .connectionStatus(ConnectionStatusType.PENDING) + .connectionStatus(ConnectionStatusType.REAUTH) .build() } @@ -19,13 +18,12 @@ class SandboxConnectionAccountUpdateParamsTest { fun body() { val params = SandboxConnectionAccountUpdateParams.builder() - .connectionStatus(ConnectionStatusType.PENDING) + .connectionStatus(ConnectionStatusType.REAUTH) .build() val body = params._body() - assertNotNull(body) - assertThat(body.connectionStatus()).contains(ConnectionStatusType.PENDING) + assertThat(body.connectionStatus()).contains(ConnectionStatusType.REAUTH) } @Test @@ -33,7 +31,5 @@ class SandboxConnectionAccountUpdateParamsTest { val params = SandboxConnectionAccountUpdateParams.builder().build() val body = params._body() - - assertNotNull(body) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxConnectionCreateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxConnectionCreateParamsTest.kt index 1e1fc9ac..86e80f36 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxConnectionCreateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxConnectionCreateParamsTest.kt @@ -2,11 +2,11 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SandboxConnectionCreateParamsTest { +internal class SandboxConnectionCreateParamsTest { @Test fun create() { @@ -30,12 +30,11 @@ class SandboxConnectionCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.providerId()).isEqualTo("provider_id") assertThat(body.authenticationType()) .contains(SandboxConnectionCreateParams.AuthenticationType.CREDENTIAL) assertThat(body.employeeSize()).contains(0L) - assertThat(body.products()).contains(listOf("string")) + assertThat(body.products().getOrNull()).containsExactly("string") } @Test @@ -44,7 +43,6 @@ class SandboxConnectionCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.providerId()).isEqualTo("provider_id") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxDirectoryCreateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxDirectoryCreateParamsTest.kt index d4b9e47f..b054e2fd 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxDirectoryCreateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxDirectoryCreateParamsTest.kt @@ -7,7 +7,7 @@ import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SandboxDirectoryCreateParamsTest { +internal class SandboxDirectoryCreateParamsTest { @Test fun create() { @@ -89,7 +89,7 @@ class SandboxDirectoryCreateParamsTest { ) .manager( SandboxDirectoryCreateParams.IndividualOrEmployment.Manager.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() ) .middleName("middle_name") @@ -211,7 +211,7 @@ class SandboxDirectoryCreateParamsTest { ) .manager( SandboxDirectoryCreateParams.IndividualOrEmployment.Manager.builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() ) .middleName("middle_name") @@ -250,124 +250,114 @@ class SandboxDirectoryCreateParamsTest { val body = params._body().getOrNull() assertThat(body) - .isEqualTo( - listOf( - SandboxDirectoryCreateParams.IndividualOrEmployment.builder() - .classCode("class_code") - .addCustomField( - SandboxDirectoryCreateParams.IndividualOrEmployment.CustomField - .builder() - .name("name") - .value(JsonValue.from(mapOf())) - .build() - ) - .department( - SandboxDirectoryCreateParams.IndividualOrEmployment.Department.builder() - .name("name") - .build() - ) - .dob("dob") - .addEmail( - SandboxDirectoryCreateParams.IndividualOrEmployment.Email.builder() - .data("data") - .type( - SandboxDirectoryCreateParams.IndividualOrEmployment.Email.Type - .WORK - ) - .build() - ) - .employment( - SandboxDirectoryCreateParams.IndividualOrEmployment.Employment.builder() - .subtype( - SandboxDirectoryCreateParams.IndividualOrEmployment.Employment - .Subtype - .FULL_TIME - ) - .type( - SandboxDirectoryCreateParams.IndividualOrEmployment.Employment - .Type - .EMPLOYEE - ) - .build() - ) - .employmentStatus( - SandboxDirectoryCreateParams.IndividualOrEmployment.EmploymentStatus - .ACTIVE - ) - .encryptedSsn("encrypted_ssn") - .endDate("end_date") - .ethnicity( - SandboxDirectoryCreateParams.IndividualOrEmployment.Ethnicity.ASIAN - ) - .firstName("first_name") - .gender(SandboxDirectoryCreateParams.IndividualOrEmployment.Gender.FEMALE) - .income( - Income.builder() - .amount(0L) - .currency("currency") - .effectiveDate("effective_date") - .unit(Income.Unit.YEARLY) - .build() - ) - .addIncomeHistory( - Income.builder() - .amount(0L) - .currency("currency") - .effectiveDate("effective_date") - .unit(Income.Unit.YEARLY) - .build() - ) - .isActive(true) - .lastName("last_name") - .latestRehireDate("latest_rehire_date") - .location( - Location.builder() - .city("city") - .country("country") - .line1("line1") - .line2("line2") - .name("name") - .postalCode("postal_code") - .sourceId("source_id") - .state("state") - .build() - ) - .manager( - SandboxDirectoryCreateParams.IndividualOrEmployment.Manager.builder() - .id("id") - .build() - ) - .middleName("middle_name") - .addPhoneNumber( - SandboxDirectoryCreateParams.IndividualOrEmployment.PhoneNumber - .builder() - .data("data") - .type( - SandboxDirectoryCreateParams.IndividualOrEmployment.PhoneNumber - .Type - .WORK - ) - .build() - ) - .preferredName("preferred_name") - .residence( - Location.builder() - .city("city") - .country("country") - .line1("line1") - .line2("line2") - .name("name") - .postalCode("postal_code") - .sourceId("source_id") - .state("state") - .build() - ) - .sourceId("source_id") - .ssn("ssn") - .startDate("start_date") - .title("title") - .build() - ) + .containsExactly( + SandboxDirectoryCreateParams.IndividualOrEmployment.builder() + .classCode("class_code") + .addCustomField( + SandboxDirectoryCreateParams.IndividualOrEmployment.CustomField.builder() + .name("name") + .value(JsonValue.from(mapOf())) + .build() + ) + .department( + SandboxDirectoryCreateParams.IndividualOrEmployment.Department.builder() + .name("name") + .build() + ) + .dob("dob") + .addEmail( + SandboxDirectoryCreateParams.IndividualOrEmployment.Email.builder() + .data("data") + .type( + SandboxDirectoryCreateParams.IndividualOrEmployment.Email.Type.WORK + ) + .build() + ) + .employment( + SandboxDirectoryCreateParams.IndividualOrEmployment.Employment.builder() + .subtype( + SandboxDirectoryCreateParams.IndividualOrEmployment.Employment + .Subtype + .FULL_TIME + ) + .type( + SandboxDirectoryCreateParams.IndividualOrEmployment.Employment.Type + .EMPLOYEE + ) + .build() + ) + .employmentStatus( + SandboxDirectoryCreateParams.IndividualOrEmployment.EmploymentStatus.ACTIVE + ) + .encryptedSsn("encrypted_ssn") + .endDate("end_date") + .ethnicity(SandboxDirectoryCreateParams.IndividualOrEmployment.Ethnicity.ASIAN) + .firstName("first_name") + .gender(SandboxDirectoryCreateParams.IndividualOrEmployment.Gender.FEMALE) + .income( + Income.builder() + .amount(0L) + .currency("currency") + .effectiveDate("effective_date") + .unit(Income.Unit.YEARLY) + .build() + ) + .addIncomeHistory( + Income.builder() + .amount(0L) + .currency("currency") + .effectiveDate("effective_date") + .unit(Income.Unit.YEARLY) + .build() + ) + .isActive(true) + .lastName("last_name") + .latestRehireDate("latest_rehire_date") + .location( + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() + ) + .manager( + SandboxDirectoryCreateParams.IndividualOrEmployment.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .middleName("middle_name") + .addPhoneNumber( + SandboxDirectoryCreateParams.IndividualOrEmployment.PhoneNumber.builder() + .data("data") + .type( + SandboxDirectoryCreateParams.IndividualOrEmployment.PhoneNumber.Type + .WORK + ) + .build() + ) + .preferredName("preferred_name") + .residence( + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() + ) + .sourceId("source_id") + .ssn("ssn") + .startDate("start_date") + .title("title") + .build() ) } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxEmploymentUpdateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxEmploymentUpdateParamsTest.kt index 6e2e0112..fbe2b905 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxEmploymentUpdateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxEmploymentUpdateParamsTest.kt @@ -3,11 +3,11 @@ package com.tryfinch.api.models import com.tryfinch.api.core.JsonValue -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SandboxEmploymentUpdateParamsTest { +internal class SandboxEmploymentUpdateParamsTest { @Test fun create() { @@ -61,7 +61,11 @@ class SandboxEmploymentUpdateParamsTest { .state("state") .build() ) - .manager(SandboxEmploymentUpdateParams.Manager.builder().id("id").build()) + .manager( + SandboxEmploymentUpdateParams.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) .middleName("middle_name") .sourceId("source_id") .startDate("start_date") @@ -69,6 +73,15 @@ class SandboxEmploymentUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = SandboxEmploymentUpdateParams.builder().individualId("individual_id").build() + + assertThat(params._pathParam(0)).isEqualTo("individual_id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -122,7 +135,11 @@ class SandboxEmploymentUpdateParamsTest { .state("state") .build() ) - .manager(SandboxEmploymentUpdateParams.Manager.builder().id("id").build()) + .manager( + SandboxEmploymentUpdateParams.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) .middleName("middle_name") .sourceId("source_id") .startDate("start_date") @@ -131,16 +148,13 @@ class SandboxEmploymentUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.classCode()).contains("class_code") - assertThat(body.customFields()) - .contains( - listOf( - SandboxEmploymentUpdateParams.CustomField.builder() - .name("name") - .value(JsonValue.from(mapOf())) - .build() - ) + assertThat(body.customFields().getOrNull()) + .containsExactly( + SandboxEmploymentUpdateParams.CustomField.builder() + .name("name") + .value(JsonValue.from(mapOf())) + .build() ) assertThat(body.department()) .contains(SandboxEmploymentUpdateParams.Department.builder().name("name").build()) @@ -164,16 +178,14 @@ class SandboxEmploymentUpdateParamsTest { .unit(Income.Unit.YEARLY) .build() ) - assertThat(body.incomeHistory()) - .contains( - listOf( - Income.builder() - .amount(0L) - .currency("currency") - .effectiveDate("effective_date") - .unit(Income.Unit.YEARLY) - .build() - ) + assertThat(body.incomeHistory().getOrNull()) + .containsExactly( + Income.builder() + .amount(0L) + .currency("currency") + .effectiveDate("effective_date") + .unit(Income.Unit.YEARLY) + .build() ) assertThat(body.isActive()).contains(true) assertThat(body.lastName()).contains("last_name") @@ -192,7 +204,11 @@ class SandboxEmploymentUpdateParamsTest { .build() ) assertThat(body.manager()) - .contains(SandboxEmploymentUpdateParams.Manager.builder().id("id").build()) + .contains( + SandboxEmploymentUpdateParams.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) assertThat(body.middleName()).contains("middle_name") assertThat(body.sourceId()).contains("source_id") assertThat(body.startDate()).contains("start_date") @@ -204,17 +220,5 @@ class SandboxEmploymentUpdateParamsTest { val params = SandboxEmploymentUpdateParams.builder().individualId("individual_id").build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = SandboxEmploymentUpdateParams.builder().individualId("individual_id").build() - assertThat(params).isNotNull - // path param "individualId" - assertThat(params.getPathParam(0)).isEqualTo("individual_id") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxIndividualUpdateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxIndividualUpdateParamsTest.kt index 28ebe7b1..65df3b36 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxIndividualUpdateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxIndividualUpdateParamsTest.kt @@ -2,11 +2,11 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SandboxIndividualUpdateParamsTest { +internal class SandboxIndividualUpdateParamsTest { @Test fun create() { @@ -48,6 +48,15 @@ class SandboxIndividualUpdateParamsTest { .build() } + @Test + fun pathParams() { + val params = SandboxIndividualUpdateParams.builder().individualId("individual_id").build() + + assertThat(params._pathParam(0)).isEqualTo("individual_id") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + @Test fun body() { val params = @@ -90,16 +99,13 @@ class SandboxIndividualUpdateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.dob()).contains("dob") - assertThat(body.emails()) - .contains( - listOf( - SandboxIndividualUpdateParams.Email.builder() - .data("data") - .type(SandboxIndividualUpdateParams.Email.Type.WORK) - .build() - ) + assertThat(body.emails().getOrNull()) + .containsExactly( + SandboxIndividualUpdateParams.Email.builder() + .data("data") + .type(SandboxIndividualUpdateParams.Email.Type.WORK) + .build() ) assertThat(body.encryptedSsn()).contains("encrypted_ssn") assertThat(body.ethnicity()).contains(SandboxIndividualUpdateParams.Ethnicity.ASIAN) @@ -107,14 +113,12 @@ class SandboxIndividualUpdateParamsTest { assertThat(body.gender()).contains(SandboxIndividualUpdateParams.Gender.FEMALE) assertThat(body.lastName()).contains("last_name") assertThat(body.middleName()).contains("middle_name") - assertThat(body.phoneNumbers()) - .contains( - listOf( - SandboxIndividualUpdateParams.PhoneNumber.builder() - .data("data") - .type(SandboxIndividualUpdateParams.PhoneNumber.Type.WORK) - .build() - ) + assertThat(body.phoneNumbers().getOrNull()) + .containsExactly( + SandboxIndividualUpdateParams.PhoneNumber.builder() + .data("data") + .type(SandboxIndividualUpdateParams.PhoneNumber.Type.WORK) + .build() ) assertThat(body.preferredName()).contains("preferred_name") assertThat(body.residence()) @@ -138,17 +142,5 @@ class SandboxIndividualUpdateParamsTest { val params = SandboxIndividualUpdateParams.builder().individualId("individual_id").build() val body = params._body() - - assertNotNull(body) - } - - @Test - fun getPathParam() { - val params = SandboxIndividualUpdateParams.builder().individualId("individual_id").build() - assertThat(params).isNotNull - // path param "individualId" - assertThat(params.getPathParam(0)).isEqualTo("individual_id") - // out-of-bound path param - assertThat(params.getPathParam(1)).isEqualTo("") } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobConfigurationRetrieveParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobConfigurationRetrieveParamsTest.kt index 297979f1..7d0606c5 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobConfigurationRetrieveParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobConfigurationRetrieveParamsTest.kt @@ -4,7 +4,7 @@ package com.tryfinch.api.models import org.junit.jupiter.api.Test -class SandboxJobConfigurationRetrieveParamsTest { +internal class SandboxJobConfigurationRetrieveParamsTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobConfigurationTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobConfigurationTest.kt index 9aceb8c2..ac396ef1 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobConfigurationTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobConfigurationTest.kt @@ -2,22 +2,42 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SandboxJobConfigurationTest { +internal class SandboxJobConfigurationTest { @Test - fun createSandboxJobConfiguration() { + fun create() { val sandboxJobConfiguration = SandboxJobConfiguration.builder() .completionStatus(SandboxJobConfiguration.CompletionStatus.COMPLETE) .type(SandboxJobConfiguration.Type.DATA_SYNC_ALL) .build() - assertThat(sandboxJobConfiguration).isNotNull + assertThat(sandboxJobConfiguration.completionStatus()) .isEqualTo(SandboxJobConfiguration.CompletionStatus.COMPLETE) assertThat(sandboxJobConfiguration.type()) .isEqualTo(SandboxJobConfiguration.Type.DATA_SYNC_ALL) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val sandboxJobConfiguration = + SandboxJobConfiguration.builder() + .completionStatus(SandboxJobConfiguration.CompletionStatus.COMPLETE) + .type(SandboxJobConfiguration.Type.DATA_SYNC_ALL) + .build() + + val roundtrippedSandboxJobConfiguration = + jsonMapper.readValue( + jsonMapper.writeValueAsString(sandboxJobConfiguration), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSandboxJobConfiguration).isEqualTo(sandboxJobConfiguration) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobConfigurationUpdateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobConfigurationUpdateParamsTest.kt index 6c748f9b..a9818e71 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobConfigurationUpdateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobConfigurationUpdateParamsTest.kt @@ -5,7 +5,7 @@ package com.tryfinch.api.models import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SandboxJobConfigurationUpdateParamsTest { +internal class SandboxJobConfigurationUpdateParamsTest { @Test fun create() { @@ -41,27 +41,4 @@ class SandboxJobConfigurationUpdateParamsTest { .build() ) } - - @Test - fun bodyWithoutOptionalFields() { - val params = - SandboxJobConfigurationUpdateParams.builder() - .sandboxJobConfiguration( - SandboxJobConfiguration.builder() - .completionStatus(SandboxJobConfiguration.CompletionStatus.COMPLETE) - .type(SandboxJobConfiguration.Type.DATA_SYNC_ALL) - .build() - ) - .build() - - val body = params._body() - - assertThat(body) - .isEqualTo( - SandboxJobConfiguration.builder() - .completionStatus(SandboxJobConfiguration.CompletionStatus.COMPLETE) - .type(SandboxJobConfiguration.Type.DATA_SYNC_ALL) - .build() - ) - } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobCreateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobCreateParamsTest.kt index 1cd761ec..f26c5c11 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobCreateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxJobCreateParamsTest.kt @@ -2,11 +2,10 @@ package com.tryfinch.api.models -import kotlin.test.assertNotNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SandboxJobCreateParamsTest { +internal class SandboxJobCreateParamsTest { @Test fun create() { @@ -20,18 +19,6 @@ class SandboxJobCreateParamsTest { val body = params._body() - assertNotNull(body) - assertThat(body.type()).isEqualTo(SandboxJobCreateParams.Type.DATA_SYNC_ALL) - } - - @Test - fun bodyWithoutOptionalFields() { - val params = - SandboxJobCreateParams.builder().type(SandboxJobCreateParams.Type.DATA_SYNC_ALL).build() - - val body = params._body() - - assertNotNull(body) assertThat(body.type()).isEqualTo(SandboxJobCreateParams.Type.DATA_SYNC_ALL) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxPaymentCreateParamsTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxPaymentCreateParamsTest.kt index 708ed715..68ea6c51 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxPaymentCreateParamsTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SandboxPaymentCreateParamsTest.kt @@ -3,11 +3,11 @@ package com.tryfinch.api.models import com.tryfinch.api.core.JsonValue -import kotlin.test.assertNotNull +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SandboxPaymentCreateParamsTest { +internal class SandboxPaymentCreateParamsTest { @Test fun create() { @@ -312,155 +312,147 @@ class SandboxPaymentCreateParamsTest { val body = params._body() - assertNotNull(body) assertThat(body.endDate()).contains("end_date") - assertThat(body.payStatements()) - .contains( - listOf( - SandboxPaymentCreateParams.PayStatement.builder() - .addEarning( - SandboxPaymentCreateParams.PayStatement.Earning.builder() - .amount(0L) - .attributes( - SandboxPaymentCreateParams.PayStatement.Earning.Attributes - .builder() - .metadata( - SandboxPaymentCreateParams.PayStatement.Earning - .Attributes - .Metadata - .builder() - .metadata( - SandboxPaymentCreateParams.PayStatement.Earning - .Attributes - .Metadata - .InnerMetadata - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("bar"), - ) - .build() - ) - .build() - ) - .build() - ) - .currency("currency") - .hours(0.0) - .name("name") - .type(SandboxPaymentCreateParams.PayStatement.Earning.Type.SALARY) - .build() - ) - .addEmployeeDeduction( - SandboxPaymentCreateParams.PayStatement.EmployeeDeduction.builder() - .amount(2000L) - .attributes( - SandboxPaymentCreateParams.PayStatement.EmployeeDeduction - .Attributes - .builder() - .metadata( - SandboxPaymentCreateParams.PayStatement - .EmployeeDeduction - .Attributes - .Metadata - .builder() - .metadata( - SandboxPaymentCreateParams.PayStatement - .EmployeeDeduction - .Attributes - .Metadata - .InnerMetadata - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("bar"), - ) - .build() - ) - .build() - ) - .build() - ) - .currency("usd") - .name("401k test") - .preTax(true) - .type(BenefitType._401K) - .build() - ) - .addEmployerContribution( - SandboxPaymentCreateParams.PayStatement.EmployerContribution.builder() - .amount(0L) - .attributes( - SandboxPaymentCreateParams.PayStatement.EmployerContribution - .Attributes - .builder() - .metadata( - SandboxPaymentCreateParams.PayStatement - .EmployerContribution - .Attributes - .Metadata - .builder() - .metadata( - SandboxPaymentCreateParams.PayStatement - .EmployerContribution - .Attributes - .Metadata - .InnerMetadata - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("bar"), - ) - .build() - ) - .build() - ) - .build() - ) - .currency("currency") - .name("name") - .type(BenefitType._401K) - .build() - ) - .grossPay(Money.builder().amount(0L).currency("currency").build()) - .individualId("b2338cfb-472f-4f72-9faa-e028c083144a") - .netPay(Money.builder().amount(0L).currency("currency").build()) - .paymentMethod(SandboxPaymentCreateParams.PayStatement.PaymentMethod.CHECK) - .addTax( - SandboxPaymentCreateParams.PayStatement.Tax.builder() - .amount(0L) - .attributes( - SandboxPaymentCreateParams.PayStatement.Tax.Attributes.builder() - .metadata( - SandboxPaymentCreateParams.PayStatement.Tax.Attributes - .Metadata - .builder() - .metadata( - SandboxPaymentCreateParams.PayStatement.Tax - .Attributes - .Metadata - .InnerMetadata - .builder() - .putAdditionalProperty( - "foo", - JsonValue.from("bar"), - ) - .build() - ) - .build() - ) - .build() - ) - .currency("currency") - .employer(true) - .name("name") - .type(SandboxPaymentCreateParams.PayStatement.Tax.Type.STATE) - .build() - ) - .totalHours(0.0) - .type(SandboxPaymentCreateParams.PayStatement.Type.REGULAR_PAYROLL) - .build() - ) + assertThat(body.payStatements().getOrNull()) + .containsExactly( + SandboxPaymentCreateParams.PayStatement.builder() + .addEarning( + SandboxPaymentCreateParams.PayStatement.Earning.builder() + .amount(0L) + .attributes( + SandboxPaymentCreateParams.PayStatement.Earning.Attributes.builder() + .metadata( + SandboxPaymentCreateParams.PayStatement.Earning.Attributes + .Metadata + .builder() + .metadata( + SandboxPaymentCreateParams.PayStatement.Earning + .Attributes + .Metadata + .InnerMetadata + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .hours(0.0) + .name("name") + .type(SandboxPaymentCreateParams.PayStatement.Earning.Type.SALARY) + .build() + ) + .addEmployeeDeduction( + SandboxPaymentCreateParams.PayStatement.EmployeeDeduction.builder() + .amount(2000L) + .attributes( + SandboxPaymentCreateParams.PayStatement.EmployeeDeduction.Attributes + .builder() + .metadata( + SandboxPaymentCreateParams.PayStatement.EmployeeDeduction + .Attributes + .Metadata + .builder() + .metadata( + SandboxPaymentCreateParams.PayStatement + .EmployeeDeduction + .Attributes + .Metadata + .InnerMetadata + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .build() + ) + .build() + ) + .currency("usd") + .name("401k test") + .preTax(true) + .type(BenefitType._401K) + .build() + ) + .addEmployerContribution( + SandboxPaymentCreateParams.PayStatement.EmployerContribution.builder() + .amount(0L) + .attributes( + SandboxPaymentCreateParams.PayStatement.EmployerContribution + .Attributes + .builder() + .metadata( + SandboxPaymentCreateParams.PayStatement.EmployerContribution + .Attributes + .Metadata + .builder() + .metadata( + SandboxPaymentCreateParams.PayStatement + .EmployerContribution + .Attributes + .Metadata + .InnerMetadata + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .name("name") + .type(BenefitType._401K) + .build() + ) + .grossPay(Money.builder().amount(0L).currency("currency").build()) + .individualId("b2338cfb-472f-4f72-9faa-e028c083144a") + .netPay(Money.builder().amount(0L).currency("currency").build()) + .paymentMethod(SandboxPaymentCreateParams.PayStatement.PaymentMethod.CHECK) + .addTax( + SandboxPaymentCreateParams.PayStatement.Tax.builder() + .amount(0L) + .attributes( + SandboxPaymentCreateParams.PayStatement.Tax.Attributes.builder() + .metadata( + SandboxPaymentCreateParams.PayStatement.Tax.Attributes + .Metadata + .builder() + .metadata( + SandboxPaymentCreateParams.PayStatement.Tax + .Attributes + .Metadata + .InnerMetadata + .builder() + .putAdditionalProperty( + "foo", + JsonValue.from("bar"), + ) + .build() + ) + .build() + ) + .build() + ) + .currency("currency") + .employer(true) + .name("name") + .type(SandboxPaymentCreateParams.PayStatement.Tax.Type.STATE) + .build() + ) + .totalHours(0.0) + .type(SandboxPaymentCreateParams.PayStatement.Type.REGULAR_PAYROLL) + .build() ) assertThat(body.startDate()).contains("start_date") } @@ -470,7 +462,5 @@ class SandboxPaymentCreateParamsTest { val params = SandboxPaymentCreateParams.builder().build() val body = params._body() - - assertNotNull(body) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SessionNewResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SessionNewResponseTest.kt index 9ddf00ba..e89800c6 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SessionNewResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SessionNewResponseTest.kt @@ -2,20 +2,40 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SessionNewResponseTest { +internal class SessionNewResponseTest { @Test - fun createSessionNewResponse() { + fun create() { val sessionNewResponse = SessionNewResponse.builder() .connectUrl("https://example.com") .sessionId("session_id") .build() - assertThat(sessionNewResponse).isNotNull + assertThat(sessionNewResponse.connectUrl()).isEqualTo("https://example.com") assertThat(sessionNewResponse.sessionId()).isEqualTo("session_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val sessionNewResponse = + SessionNewResponse.builder() + .connectUrl("https://example.com") + .sessionId("session_id") + .build() + + val roundtrippedSessionNewResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(sessionNewResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSessionNewResponse).isEqualTo(sessionNewResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SessionReauthenticateResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SessionReauthenticateResponseTest.kt index e260ceea..62068842 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SessionReauthenticateResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SessionReauthenticateResponseTest.kt @@ -2,20 +2,41 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SessionReauthenticateResponseTest { +internal class SessionReauthenticateResponseTest { @Test - fun createSessionReauthenticateResponse() { + fun create() { val sessionReauthenticateResponse = SessionReauthenticateResponse.builder() .connectUrl("https://example.com") .sessionId("session_id") .build() - assertThat(sessionReauthenticateResponse).isNotNull + assertThat(sessionReauthenticateResponse.connectUrl()).isEqualTo("https://example.com") assertThat(sessionReauthenticateResponse.sessionId()).isEqualTo("session_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val sessionReauthenticateResponse = + SessionReauthenticateResponse.builder() + .connectUrl("https://example.com") + .sessionId("session_id") + .build() + + val roundtrippedSessionReauthenticateResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(sessionReauthenticateResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSessionReauthenticateResponse) + .isEqualTo(sessionReauthenticateResponse) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SupportPerBenefitTypeTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SupportPerBenefitTypeTest.kt index 17971b5a..16ef24a4 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SupportPerBenefitTypeTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SupportPerBenefitTypeTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SupportPerBenefitTypeTest { +internal class SupportPerBenefitTypeTest { @Test - fun createSupportPerBenefitType() { + fun create() { val supportPerBenefitType = SupportPerBenefitType.builder() .companyBenefits( @@ -28,7 +30,7 @@ class SupportPerBenefitTypeTest { .build() ) .build() - assertThat(supportPerBenefitType).isNotNull + assertThat(supportPerBenefitType.companyBenefits()) .contains( OperationSupportMatrix.builder() @@ -48,4 +50,36 @@ class SupportPerBenefitTypeTest { .build() ) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val supportPerBenefitType = + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + + val roundtrippedSupportPerBenefitType = + jsonMapper.readValue( + jsonMapper.writeValueAsString(supportPerBenefitType), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSupportPerBenefitType).isEqualTo(supportPerBenefitType) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SupportedBenefitTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SupportedBenefitTest.kt index 56ad5909..147c8735 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SupportedBenefitTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/SupportedBenefitTest.kt @@ -2,13 +2,16 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper +import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class SupportedBenefitTest { +internal class SupportedBenefitTest { @Test - fun createSupportedBenefit() { + fun create() { val supportedBenefit = SupportedBenefit.builder() .annualMaximum(true) @@ -20,17 +23,42 @@ class SupportedBenefitTest { .addHsaContributionLimit(SupportedBenefit.HsaContributionLimit.INDIVIDUAL) .type(BenefitType._401K) .build() - assertThat(supportedBenefit).isNotNull + assertThat(supportedBenefit.annualMaximum()).contains(true) assertThat(supportedBenefit.catchUp()).contains(true) - assertThat(supportedBenefit.companyContribution().get()) + assertThat(supportedBenefit.companyContribution().getOrNull()) .containsExactly(SupportedBenefit.CompanyContribution.FIXED) assertThat(supportedBenefit.description()).contains("description") - assertThat(supportedBenefit.employeeDeduction().get()) + assertThat(supportedBenefit.employeeDeduction().getOrNull()) .containsExactly(SupportedBenefit.EmployeeDeduction.FIXED) - assertThat(supportedBenefit.frequencies().get()).containsExactly(BenefitFrequency.ONE_TIME) - assertThat(supportedBenefit.hsaContributionLimit().get()) + assertThat(supportedBenefit.frequencies().getOrNull()) + .containsExactly(BenefitFrequency.ONE_TIME) + assertThat(supportedBenefit.hsaContributionLimit().getOrNull()) .containsExactly(SupportedBenefit.HsaContributionLimit.INDIVIDUAL) assertThat(supportedBenefit.type()).contains(BenefitType._401K) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val supportedBenefit = + SupportedBenefit.builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution(SupportedBenefit.CompanyContribution.FIXED) + .description("description") + .addEmployeeDeduction(SupportedBenefit.EmployeeDeduction.FIXED) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit(SupportedBenefit.HsaContributionLimit.INDIVIDUAL) + .type(BenefitType._401K) + .build() + + val roundtrippedSupportedBenefit = + jsonMapper.readValue( + jsonMapper.writeValueAsString(supportedBenefit), + jacksonTypeRef(), + ) + + assertThat(roundtrippedSupportedBenefit).isEqualTo(supportedBenefit) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/UnenrolledIndividualTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/UnenrolledIndividualTest.kt index 6f4f0b7f..98753d93 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/UnenrolledIndividualTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/UnenrolledIndividualTest.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class UnenrolledIndividualTest { +internal class UnenrolledIndividualTest { @Test - fun createUnenrolledIndividual() { + fun create() { val unenrolledIndividual = UnenrolledIndividual.builder() .body( @@ -21,7 +23,7 @@ class UnenrolledIndividualTest { .code(0L) .individualId("individual_id") .build() - assertThat(unenrolledIndividual).isNotNull + assertThat(unenrolledIndividual.body()) .contains( UnenrolledIndividual.Body.builder() @@ -33,4 +35,29 @@ class UnenrolledIndividualTest { assertThat(unenrolledIndividual.code()).contains(0L) assertThat(unenrolledIndividual.individualId()).contains("individual_id") } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val unenrolledIndividual = + UnenrolledIndividual.builder() + .body( + UnenrolledIndividual.Body.builder() + .finchCode("finch_code") + .message("message") + .name("name") + .build() + ) + .code(0L) + .individualId("individual_id") + .build() + + val roundtrippedUnenrolledIndividual = + jsonMapper.readValue( + jsonMapper.writeValueAsString(unenrolledIndividual), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUnenrolledIndividual).isEqualTo(unenrolledIndividual) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/UpdateCompanyBenefitResponseTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/UpdateCompanyBenefitResponseTest.kt index 818d0edf..dcbaa6e5 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/UpdateCompanyBenefitResponseTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/UpdateCompanyBenefitResponseTest.kt @@ -2,16 +2,38 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class UpdateCompanyBenefitResponseTest { +internal class UpdateCompanyBenefitResponseTest { @Test - fun createUpdateCompanyBenefitResponse() { + fun create() { val updateCompanyBenefitResponse = - UpdateCompanyBenefitResponse.builder().benefitId("benefit_id").build() - assertThat(updateCompanyBenefitResponse).isNotNull - assertThat(updateCompanyBenefitResponse.benefitId()).isEqualTo("benefit_id") + UpdateCompanyBenefitResponse.builder() + .benefitId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + assertThat(updateCompanyBenefitResponse.benefitId()) + .isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val updateCompanyBenefitResponse = + UpdateCompanyBenefitResponse.builder() + .benefitId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val roundtrippedUpdateCompanyBenefitResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(updateCompanyBenefitResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedUpdateCompanyBenefitResponse).isEqualTo(updateCompanyBenefitResponse) } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/W42005Test.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/W42005Test.kt index 4a7f6313..83299435 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/W42005Test.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/W42005Test.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class W42005Test { +internal class W42005Test { @Test - fun createW42005() { + fun create() { val w42005 = W42005.builder() .data( @@ -23,7 +25,7 @@ class W42005Test { .type(W42005.Type.W4_2005) .year(0.0) .build() - assertThat(w42005).isNotNull + assertThat(w42005.data()) .contains( W42005.Data.builder() @@ -37,4 +39,28 @@ class W42005Test { assertThat(w42005.type()).contains(W42005.Type.W4_2005) assertThat(w42005.year()).contains(0.0) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val w42005 = + W42005.builder() + .data( + W42005.Data.builder() + .additionalWithholding(0L) + .exemption(W42005.Data.Exemption.EXEMPT) + .filingStatus(W42005.Data.FilingStatus.MARRIED) + .individualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .totalNumberOfAllowances(0L) + .build() + ) + .type(W42005.Type.W4_2005) + .year(0.0) + .build() + + val roundtrippedW42005 = + jsonMapper.readValue(jsonMapper.writeValueAsString(w42005), jacksonTypeRef()) + + assertThat(roundtrippedW42005).isEqualTo(w42005) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/W42020Test.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/W42020Test.kt index 227e9d74..40c7a6f5 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/W42020Test.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/W42020Test.kt @@ -2,13 +2,15 @@ package com.tryfinch.api.models +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.jsonMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class W42020Test { +internal class W42020Test { @Test - fun createW42020() { + fun create() { val w42020 = W42020.builder() .data( @@ -26,7 +28,7 @@ class W42020Test { .type(W42020.Type.W4_2020) .year(0.0) .build() - assertThat(w42020).isNotNull + assertThat(w42020.data()) .contains( W42020.Data.builder() @@ -43,4 +45,31 @@ class W42020Test { assertThat(w42020.type()).contains(W42020.Type.W4_2020) assertThat(w42020.year()).contains(0.0) } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val w42020 = + W42020.builder() + .data( + W42020.Data.builder() + .amountForOtherDependents(0L) + .amountForQualifyingChildrenUnder17(0L) + .deductions(0L) + .extraWithholding(0L) + .filingStatus(W42020.Data.FilingStatus.HEAD_OF_HOUSEHOLD) + .individualId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .otherIncome(0L) + .totalClaimDependentAndOtherCredits(0L) + .build() + ) + .type(W42020.Type.W4_2020) + .year(0.0) + .build() + + val roundtrippedW42020 = + jsonMapper.readValue(jsonMapper.writeValueAsString(w42020), jacksonTypeRef()) + + assertThat(roundtrippedW42020).isEqualTo(w42020) + } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/models/WebhookEventTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/WebhookEventTest.kt new file mode 100644 index 00000000..31778dac --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/models/WebhookEventTest.kt @@ -0,0 +1,2607 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.models + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.core.jsonMapper +import com.tryfinch.api.errors.FinchInvalidDataException +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class WebhookEventTest { + + @Test + fun ofAccountUpdated() { + val accountUpdated = + AccountUpdateEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + AccountUpdateEvent.Data.builder() + .authenticationMethod( + AccountUpdateEvent.Data.AuthenticationMethod.builder() + .benefitsSupport( + BenefitsSupport.builder() + .commuter( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .customPostTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .customPreTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .fsaDependentCare( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .fsaMedical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .hsaPost( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .hsaPre( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Dental( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Medical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .s125Vision( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .simple( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .simpleIra( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create(OperationSupport.SUPPORTED) + .delete(OperationSupport.SUPPORTED) + .read(OperationSupport.SUPPORTED) + .update(OperationSupport.SUPPORTED) + .build() + ) + .build() + ) + .build() + ) + .build() + ) + .supportedFields( + AccountUpdateEvent.Data.AuthenticationMethod.SupportedFields + .builder() + .company( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .builder() + .id(true) + .accounts( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Accounts + .builder() + .accountName(true) + .accountNumber(true) + .accountType(true) + .institutionName(true) + .routingNumber(true) + .build() + ) + .departments( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Departments + .builder() + .name(true) + .parent( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Departments + .Parent + .builder() + .name(true) + .build() + ) + .build() + ) + .ein(true) + .entity( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Entity + .builder() + .subtype(true) + .type(true) + .build() + ) + .legalName(true) + .locations( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Locations + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .primaryEmail(true) + .primaryPhoneNumber(true) + .build() + ) + .directory( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .builder() + .individuals( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Individuals + .builder() + .id(true) + .department(true) + .firstName(true) + .isActive(true) + .lastName(true) + .manager( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Individuals + .Manager + .builder() + .id(true) + .build() + ) + .middleName(true) + .build() + ) + .paging( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Paging + .builder() + .count(true) + .offset(true) + .build() + ) + .build() + ) + .employment( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .builder() + .id(true) + .classCode(true) + .customFields(true) + .department( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Department + .builder() + .name(true) + .build() + ) + .employment( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Employment + .builder() + .subtype(true) + .type(true) + .build() + ) + .employmentStatus(true) + .endDate(true) + .firstName(true) + .income( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Income + .builder() + .amount(true) + .currency(true) + .unit(true) + .build() + ) + .incomeHistory(true) + .isActive(true) + .lastName(true) + .location( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Location + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .manager( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Manager + .builder() + .id(true) + .build() + ) + .middleName(true) + .startDate(true) + .title(true) + .build() + ) + .individual( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .builder() + .id(true) + .dob(true) + .emails( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .Emails + .builder() + .data(true) + .type(true) + .build() + ) + .encryptedSsn(true) + .ethnicity(true) + .firstName(true) + .gender(true) + .lastName(true) + .middleName(true) + .phoneNumbers( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .PhoneNumbers + .builder() + .data(true) + .type(true) + .build() + ) + .preferredName(true) + .residence( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .Residence + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .ssn(true) + .build() + ) + .payGroup( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayGroupFields + .builder() + .id(true) + .individualIds(true) + .name(true) + .payFrequencies(true) + .build() + ) + .payStatement( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .builder() + .paging( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .Paging + .builder() + .count(true) + .offset(true) + .build() + ) + .payStatements( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .builder() + .earnings( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .Earnings + .builder() + .amount(true) + .currency(true) + .name(true) + .type(true) + .build() + ) + .employeeDeductions( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .EmployeeDeductions + .builder() + .amount(true) + .currency(true) + .name(true) + .preTax(true) + .type(true) + .build() + ) + .employerContributions( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .EmployerContributions + .builder() + .amount(true) + .currency(true) + .name(true) + .build() + ) + .grossPay(true) + .individualId(true) + .netPay(true) + .paymentMethod(true) + .taxes( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .Taxes + .builder() + .amount(true) + .currency(true) + .employer(true) + .name(true) + .type(true) + .build() + ) + .totalHours(true) + .type(true) + .build() + ) + .build() + ) + .payment( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPaymentFields + .builder() + .id(true) + .companyDebit(true) + .debitDate(true) + .employeeTaxes(true) + .employerTaxes(true) + .grossPay(true) + .individualIds(true) + .netPay(true) + .payDate(true) + .payFrequencies(true) + .payGroupIds(true) + .payPeriod( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPaymentFields + .PayPeriod + .builder() + .endDate(true) + .startDate(true) + .build() + ) + .build() + ) + .build() + ) + .type(AccountUpdateEvent.Data.AuthenticationMethod.Type.ASSISTED) + .build() + ) + .status(ConnectionStatusType.PENDING) + .build() + ) + .eventType(AccountUpdateEvent.EventType.ACCOUNT_UPDATED) + .build() + + val webhookEvent = WebhookEvent.ofAccountUpdated(accountUpdated) + + assertThat(webhookEvent.accountUpdated()).contains(accountUpdated) + assertThat(webhookEvent.jobCompletion()).isEmpty + assertThat(webhookEvent.companyUpdated()).isEmpty + assertThat(webhookEvent.directory()).isEmpty + assertThat(webhookEvent.employment()).isEmpty + assertThat(webhookEvent.individual()).isEmpty + assertThat(webhookEvent.payment()).isEmpty + assertThat(webhookEvent.payStatement()).isEmpty + } + + @Test + fun ofAccountUpdatedRoundtrip() { + val jsonMapper = jsonMapper() + val webhookEvent = + WebhookEvent.ofAccountUpdated( + AccountUpdateEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + AccountUpdateEvent.Data.builder() + .authenticationMethod( + AccountUpdateEvent.Data.AuthenticationMethod.builder() + .benefitsSupport( + BenefitsSupport.builder() + .commuter( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .build() + ) + .build() + ) + .customPostTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .build() + ) + .build() + ) + .customPreTax( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .build() + ) + .build() + ) + .fsaDependentCare( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .build() + ) + .build() + ) + .fsaMedical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .build() + ) + .build() + ) + .hsaPost( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .build() + ) + .build() + ) + .hsaPre( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .build() + ) + .build() + ) + .s125Dental( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .build() + ) + .build() + ) + .s125Medical( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .build() + ) + .build() + ) + .s125Vision( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .build() + ) + .build() + ) + .simple( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .build() + ) + .build() + ) + .simpleIra( + BenefitFeaturesAndOperations.builder() + .supportedFeatures( + BenefitFeaturesAndOperations.BenefitFeature + .builder() + .annualMaximum(true) + .catchUp(true) + .addCompanyContribution( + BenefitFeaturesAndOperations + .BenefitFeature + .CompanyContribution + .FIXED + ) + .description("description") + .addEmployeeDeduction( + BenefitFeaturesAndOperations + .BenefitFeature + .EmployeeDeduction + .FIXED + ) + .addFrequency(BenefitFrequency.ONE_TIME) + .addHsaContributionLimit( + BenefitFeaturesAndOperations + .BenefitFeature + .HsaContributionLimit + .INDIVIDUAL + ) + .build() + ) + .supportedOperations( + SupportPerBenefitType.builder() + .companyBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .individualBenefits( + OperationSupportMatrix.builder() + .create( + OperationSupport.SUPPORTED + ) + .delete( + OperationSupport.SUPPORTED + ) + .read( + OperationSupport.SUPPORTED + ) + .update( + OperationSupport.SUPPORTED + ) + .build() + ) + .build() + ) + .build() + ) + .build() + ) + .supportedFields( + AccountUpdateEvent.Data.AuthenticationMethod.SupportedFields + .builder() + .company( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .builder() + .id(true) + .accounts( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Accounts + .builder() + .accountName(true) + .accountNumber(true) + .accountType(true) + .institutionName(true) + .routingNumber(true) + .build() + ) + .departments( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Departments + .builder() + .name(true) + .parent( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Departments + .Parent + .builder() + .name(true) + .build() + ) + .build() + ) + .ein(true) + .entity( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Entity + .builder() + .subtype(true) + .type(true) + .build() + ) + .legalName(true) + .locations( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedCompanyFields + .Locations + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .primaryEmail(true) + .primaryPhoneNumber(true) + .build() + ) + .directory( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .builder() + .individuals( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Individuals + .builder() + .id(true) + .department(true) + .firstName(true) + .isActive(true) + .lastName(true) + .manager( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Individuals + .Manager + .builder() + .id(true) + .build() + ) + .middleName(true) + .build() + ) + .paging( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedDirectoryFields + .Paging + .builder() + .count(true) + .offset(true) + .build() + ) + .build() + ) + .employment( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .builder() + .id(true) + .classCode(true) + .customFields(true) + .department( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Department + .builder() + .name(true) + .build() + ) + .employment( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Employment + .builder() + .subtype(true) + .type(true) + .build() + ) + .employmentStatus(true) + .endDate(true) + .firstName(true) + .income( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Income + .builder() + .amount(true) + .currency(true) + .unit(true) + .build() + ) + .incomeHistory(true) + .isActive(true) + .lastName(true) + .location( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Location + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .manager( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedEmploymentFields + .Manager + .builder() + .id(true) + .build() + ) + .middleName(true) + .startDate(true) + .title(true) + .build() + ) + .individual( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .builder() + .id(true) + .dob(true) + .emails( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .Emails + .builder() + .data(true) + .type(true) + .build() + ) + .encryptedSsn(true) + .ethnicity(true) + .firstName(true) + .gender(true) + .lastName(true) + .middleName(true) + .phoneNumbers( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .PhoneNumbers + .builder() + .data(true) + .type(true) + .build() + ) + .preferredName(true) + .residence( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedIndividualFields + .Residence + .builder() + .city(true) + .country(true) + .line1(true) + .line2(true) + .postalCode(true) + .state(true) + .build() + ) + .ssn(true) + .build() + ) + .payGroup( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayGroupFields + .builder() + .id(true) + .individualIds(true) + .name(true) + .payFrequencies(true) + .build() + ) + .payStatement( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .builder() + .paging( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .Paging + .builder() + .count(true) + .offset(true) + .build() + ) + .payStatements( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .builder() + .earnings( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .Earnings + .builder() + .amount(true) + .currency(true) + .name(true) + .type(true) + .build() + ) + .employeeDeductions( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .EmployeeDeductions + .builder() + .amount(true) + .currency(true) + .name(true) + .preTax(true) + .type(true) + .build() + ) + .employerContributions( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .EmployerContributions + .builder() + .amount(true) + .currency(true) + .name(true) + .build() + ) + .grossPay(true) + .individualId(true) + .netPay(true) + .paymentMethod(true) + .taxes( + AccountUpdateEvent.Data + .AuthenticationMethod + .SupportedFields + .SupportedPayStatementFields + .PayStatements + .Taxes + .builder() + .amount(true) + .currency(true) + .employer(true) + .name(true) + .type(true) + .build() + ) + .totalHours(true) + .type(true) + .build() + ) + .build() + ) + .payment( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPaymentFields + .builder() + .id(true) + .companyDebit(true) + .debitDate(true) + .employeeTaxes(true) + .employerTaxes(true) + .grossPay(true) + .individualIds(true) + .netPay(true) + .payDate(true) + .payFrequencies(true) + .payGroupIds(true) + .payPeriod( + AccountUpdateEvent.Data.AuthenticationMethod + .SupportedFields + .SupportedPaymentFields + .PayPeriod + .builder() + .endDate(true) + .startDate(true) + .build() + ) + .build() + ) + .build() + ) + .type( + AccountUpdateEvent.Data.AuthenticationMethod.Type.ASSISTED + ) + .build() + ) + .status(ConnectionStatusType.PENDING) + .build() + ) + .eventType(AccountUpdateEvent.EventType.ACCOUNT_UPDATED) + .build() + ) + + val roundtrippedWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(webhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedWebhookEvent).isEqualTo(webhookEvent) + } + + @Test + fun ofJobCompletion() { + val jobCompletion = + JobCompletionEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(JobCompletionEvent.Data.builder().jobId("job_id").jobUrl("job_url").build()) + .eventType(JobCompletionEvent.EventType.JOB_BENEFIT_CREATE_COMPLETED) + .build() + + val webhookEvent = WebhookEvent.ofJobCompletion(jobCompletion) + + assertThat(webhookEvent.accountUpdated()).isEmpty + assertThat(webhookEvent.jobCompletion()).contains(jobCompletion) + assertThat(webhookEvent.companyUpdated()).isEmpty + assertThat(webhookEvent.directory()).isEmpty + assertThat(webhookEvent.employment()).isEmpty + assertThat(webhookEvent.individual()).isEmpty + assertThat(webhookEvent.payment()).isEmpty + assertThat(webhookEvent.payStatement()).isEmpty + } + + @Test + fun ofJobCompletionRoundtrip() { + val jsonMapper = jsonMapper() + val webhookEvent = + WebhookEvent.ofJobCompletion( + JobCompletionEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + JobCompletionEvent.Data.builder().jobId("job_id").jobUrl("job_url").build() + ) + .eventType(JobCompletionEvent.EventType.JOB_BENEFIT_CREATE_COMPLETED) + .build() + ) + + val roundtrippedWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(webhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedWebhookEvent).isEqualTo(webhookEvent) + } + + @Test + fun ofCompanyUpdated() { + val companyUpdated = + CompanyEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + CompanyEvent.Data.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .eventType(CompanyEvent.EventType.COMPANY_UPDATED) + .build() + + val webhookEvent = WebhookEvent.ofCompanyUpdated(companyUpdated) + + assertThat(webhookEvent.accountUpdated()).isEmpty + assertThat(webhookEvent.jobCompletion()).isEmpty + assertThat(webhookEvent.companyUpdated()).contains(companyUpdated) + assertThat(webhookEvent.directory()).isEmpty + assertThat(webhookEvent.employment()).isEmpty + assertThat(webhookEvent.individual()).isEmpty + assertThat(webhookEvent.payment()).isEmpty + assertThat(webhookEvent.payStatement()).isEmpty + } + + @Test + fun ofCompanyUpdatedRoundtrip() { + val jsonMapper = jsonMapper() + val webhookEvent = + WebhookEvent.ofCompanyUpdated( + CompanyEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + CompanyEvent.Data.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .eventType(CompanyEvent.EventType.COMPANY_UPDATED) + .build() + ) + + val roundtrippedWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(webhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedWebhookEvent).isEqualTo(webhookEvent) + } + + @Test + fun ofDirectory() { + val directory = + DirectoryEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(DirectoryEvent.Data.builder().individualId("individual_id").build()) + .eventType(DirectoryEvent.EventType.DIRECTORY_CREATED) + .build() + + val webhookEvent = WebhookEvent.ofDirectory(directory) + + assertThat(webhookEvent.accountUpdated()).isEmpty + assertThat(webhookEvent.jobCompletion()).isEmpty + assertThat(webhookEvent.companyUpdated()).isEmpty + assertThat(webhookEvent.directory()).contains(directory) + assertThat(webhookEvent.employment()).isEmpty + assertThat(webhookEvent.individual()).isEmpty + assertThat(webhookEvent.payment()).isEmpty + assertThat(webhookEvent.payStatement()).isEmpty + } + + @Test + fun ofDirectoryRoundtrip() { + val jsonMapper = jsonMapper() + val webhookEvent = + WebhookEvent.ofDirectory( + DirectoryEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(DirectoryEvent.Data.builder().individualId("individual_id").build()) + .eventType(DirectoryEvent.EventType.DIRECTORY_CREATED) + .build() + ) + + val roundtrippedWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(webhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedWebhookEvent).isEqualTo(webhookEvent) + } + + @Test + fun ofEmployment() { + val employment = + EmploymentEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(EmploymentEvent.Data.builder().individualId("individual_id").build()) + .eventType(EmploymentEvent.EventType.EMPLOYMENT_CREATED) + .build() + + val webhookEvent = WebhookEvent.ofEmployment(employment) + + assertThat(webhookEvent.accountUpdated()).isEmpty + assertThat(webhookEvent.jobCompletion()).isEmpty + assertThat(webhookEvent.companyUpdated()).isEmpty + assertThat(webhookEvent.directory()).isEmpty + assertThat(webhookEvent.employment()).contains(employment) + assertThat(webhookEvent.individual()).isEmpty + assertThat(webhookEvent.payment()).isEmpty + assertThat(webhookEvent.payStatement()).isEmpty + } + + @Test + fun ofEmploymentRoundtrip() { + val jsonMapper = jsonMapper() + val webhookEvent = + WebhookEvent.ofEmployment( + EmploymentEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(EmploymentEvent.Data.builder().individualId("individual_id").build()) + .eventType(EmploymentEvent.EventType.EMPLOYMENT_CREATED) + .build() + ) + + val roundtrippedWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(webhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedWebhookEvent).isEqualTo(webhookEvent) + } + + @Test + fun ofIndividual() { + val individual = + IndividualEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(IndividualEvent.Data.builder().individualId("individual_id").build()) + .eventType(IndividualEvent.EventType.INDIVIDUAL_CREATED) + .build() + + val webhookEvent = WebhookEvent.ofIndividual(individual) + + assertThat(webhookEvent.accountUpdated()).isEmpty + assertThat(webhookEvent.jobCompletion()).isEmpty + assertThat(webhookEvent.companyUpdated()).isEmpty + assertThat(webhookEvent.directory()).isEmpty + assertThat(webhookEvent.employment()).isEmpty + assertThat(webhookEvent.individual()).contains(individual) + assertThat(webhookEvent.payment()).isEmpty + assertThat(webhookEvent.payStatement()).isEmpty + } + + @Test + fun ofIndividualRoundtrip() { + val jsonMapper = jsonMapper() + val webhookEvent = + WebhookEvent.ofIndividual( + IndividualEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data(IndividualEvent.Data.builder().individualId("individual_id").build()) + .eventType(IndividualEvent.EventType.INDIVIDUAL_CREATED) + .build() + ) + + val roundtrippedWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(webhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedWebhookEvent).isEqualTo(webhookEvent) + } + + @Test + fun ofPayment() { + val payment = + PaymentEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + PaymentEvent.PaymentIdentifiers.builder() + .payDate("pay_date") + .paymentId("payment_id") + .build() + ) + .eventType(PaymentEvent.EventType.PAYMENT_CREATED) + .build() + + val webhookEvent = WebhookEvent.ofPayment(payment) + + assertThat(webhookEvent.accountUpdated()).isEmpty + assertThat(webhookEvent.jobCompletion()).isEmpty + assertThat(webhookEvent.companyUpdated()).isEmpty + assertThat(webhookEvent.directory()).isEmpty + assertThat(webhookEvent.employment()).isEmpty + assertThat(webhookEvent.individual()).isEmpty + assertThat(webhookEvent.payment()).contains(payment) + assertThat(webhookEvent.payStatement()).isEmpty + } + + @Test + fun ofPaymentRoundtrip() { + val jsonMapper = jsonMapper() + val webhookEvent = + WebhookEvent.ofPayment( + PaymentEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + PaymentEvent.PaymentIdentifiers.builder() + .payDate("pay_date") + .paymentId("payment_id") + .build() + ) + .eventType(PaymentEvent.EventType.PAYMENT_CREATED) + .build() + ) + + val roundtrippedWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(webhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedWebhookEvent).isEqualTo(webhookEvent) + } + + @Test + fun ofPayStatement() { + val payStatement = + PayStatementEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + PayStatementEvent.Data.builder() + .individualId("individual_id") + .paymentId("payment_id") + .build() + ) + .eventType(PayStatementEvent.EventType.PAY_STATEMENT_CREATED) + .build() + + val webhookEvent = WebhookEvent.ofPayStatement(payStatement) + + assertThat(webhookEvent.accountUpdated()).isEmpty + assertThat(webhookEvent.jobCompletion()).isEmpty + assertThat(webhookEvent.companyUpdated()).isEmpty + assertThat(webhookEvent.directory()).isEmpty + assertThat(webhookEvent.employment()).isEmpty + assertThat(webhookEvent.individual()).isEmpty + assertThat(webhookEvent.payment()).isEmpty + assertThat(webhookEvent.payStatement()).contains(payStatement) + } + + @Test + fun ofPayStatementRoundtrip() { + val jsonMapper = jsonMapper() + val webhookEvent = + WebhookEvent.ofPayStatement( + PayStatementEvent.builder() + .accountId("account_id") + .companyId("company_id") + .connectionId("connection_id") + .data( + PayStatementEvent.Data.builder() + .individualId("individual_id") + .paymentId("payment_id") + .build() + ) + .eventType(PayStatementEvent.EventType.PAY_STATEMENT_CREATED) + .build() + ) + + val roundtrippedWebhookEvent = + jsonMapper.readValue( + jsonMapper.writeValueAsString(webhookEvent), + jacksonTypeRef(), + ) + + assertThat(roundtrippedWebhookEvent).isEqualTo(webhookEvent) + } + + enum class IncompatibleJsonShapeTestCase(val value: JsonValue) { + BOOLEAN(JsonValue.from(false)), + STRING(JsonValue.from("invalid")), + INTEGER(JsonValue.from(-1)), + FLOAT(JsonValue.from(3.14)), + ARRAY(JsonValue.from(listOf("invalid", "array"))), + } + + @ParameterizedTest + @EnumSource + fun incompatibleJsonShapeDeserializesToUnknown(testCase: IncompatibleJsonShapeTestCase) { + val webhookEvent = jsonMapper().convertValue(testCase.value, jacksonTypeRef()) + + val e = assertThrows { webhookEvent.validate() } + assertThat(e).hasMessageStartingWith("Unknown ") + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/ErrorHandlingTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/ErrorHandlingTest.kt index a51b273f..59b76d6a 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/ErrorHandlingTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/ErrorHandlingTest.kt @@ -2,10 +2,8 @@ package com.tryfinch.api.services -import com.fasterxml.jackson.databind.json.JsonMapper import com.github.tomakehurst.wiremock.client.WireMock.anyUrl import com.github.tomakehurst.wiremock.client.WireMock.get -import com.github.tomakehurst.wiremock.client.WireMock.ok import com.github.tomakehurst.wiremock.client.WireMock.status import com.github.tomakehurst.wiremock.client.WireMock.stubFor import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo @@ -16,7 +14,6 @@ import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.http.Headers import com.tryfinch.api.core.jsonMapper import com.tryfinch.api.errors.BadRequestException -import com.tryfinch.api.errors.FinchError import com.tryfinch.api.errors.FinchException import com.tryfinch.api.errors.InternalServerException import com.tryfinch.api.errors.NotFoundException @@ -25,22 +22,27 @@ import com.tryfinch.api.errors.RateLimitException import com.tryfinch.api.errors.UnauthorizedException import com.tryfinch.api.errors.UnexpectedStatusCodeException import com.tryfinch.api.errors.UnprocessableEntityException -import com.tryfinch.api.models.Company -import com.tryfinch.api.models.HrisCompanyRetrieveParams -import com.tryfinch.api.models.Location import org.assertj.core.api.Assertions.assertThat -import org.assertj.core.api.Assertions.assertThatThrownBy -import org.assertj.core.api.InstanceOfAssertFactories +import org.assertj.core.api.Assertions.entry import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows @WireMockTest -class ErrorHandlingTest { +internal class ErrorHandlingTest { - private val JSON_MAPPER: JsonMapper = jsonMapper() + companion object { - private val FINCH_ERROR: FinchError = - FinchError.builder().putAdditionalProperty("key", JsonValue.from("value")).build() + private val ERROR_JSON: JsonValue = JsonValue.from(mapOf("errorProperty" to "42")) + + private val ERROR_JSON_BYTES: ByteArray = jsonMapper().writeValueAsBytes(ERROR_JSON) + + private const val HEADER_NAME: String = "Error-Header" + + private const val HEADER_VALUE: String = "42" + + private const val NOT_JSON: String = "Not JSON" + } private lateinit var client: FinchClient @@ -48,317 +50,158 @@ class ErrorHandlingTest { fun beforeEach(wmRuntimeInfo: WireMockRuntimeInfo) { client = FinchOkHttpClient.builder() - .baseUrl(wmRuntimeInfo.getHttpBaseUrl()) + .baseUrl(wmRuntimeInfo.httpBaseUrl) .accessToken("My Access Token") - .clientId("4ab15e51-11ad-49f4-acae-f343b7794375") - .clientSecret("My Client Secret") - .webhookSecret("My Webhook Secret") .build() } @Test - fun companiesRetrieve200() { - val params = HrisCompanyRetrieveParams.builder().build() - - val expected = - Company.builder() - .id("id") - .addAccount( - Company.Account.builder() - .accountName("account_name") - .accountNumber("account_number") - .accountType(Company.Account.AccountType.CHECKING) - .institutionName("institution_name") - .routingNumber("routing_number") - .build() - ) - .addDepartment( - Company.Department.builder() - .name("name") - .parent(Company.Department.Parent.builder().name("name").build()) - .build() - ) - .ein("ein") - .entity( - Company.Entity.builder() - .subtype(Company.Entity.Subtype.S_CORPORATION) - .type(Company.Entity.Type.LLC) - .build() - ) - .legalName("legal_name") - .addLocation( - Location.builder() - .city("city") - .country("country") - .line1("line1") - .line2("line2") - .name("name") - .postalCode("postal_code") - .sourceId("source_id") - .state("state") - .build() + fun companyRetrieve400() { + val companyService = client.hris().company() + stubFor( + get(anyUrl()) + .willReturn( + status(400).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) ) - .primaryEmail("primary_email") - .primaryPhoneNumber("primary_phone_number") - .build() + ) - stubFor(get(anyUrl()).willReturn(ok().withBody(toJson(expected)))) + val e = assertThrows { companyService.retrieve() } - assertThat(client.hris().company().retrieve(params)).isEqualTo(expected) + assertThat(e.statusCode()).isEqualTo(400) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun companiesRetrieve400() { - val params = HrisCompanyRetrieveParams.builder().build() - + fun companyRetrieve401() { + val companyService = client.hris().company() stubFor( get(anyUrl()) - .willReturn(status(400).withHeader("Foo", "Bar").withBody(toJson(FINCH_ERROR))) + .willReturn( + status(401).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.hris().company().retrieve(params) }) - .satisfies({ e -> - assertBadRequest(e, Headers.builder().put("Foo", "Bar").build(), FINCH_ERROR) - }) + val e = assertThrows { companyService.retrieve() } + + assertThat(e.statusCode()).isEqualTo(401) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun companiesRetrieve401() { - val params = HrisCompanyRetrieveParams.builder().build() - + fun companyRetrieve403() { + val companyService = client.hris().company() stubFor( get(anyUrl()) - .willReturn(status(401).withHeader("Foo", "Bar").withBody(toJson(FINCH_ERROR))) + .willReturn( + status(403).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.hris().company().retrieve(params) }) - .satisfies({ e -> - assertUnauthorized(e, Headers.builder().put("Foo", "Bar").build(), FINCH_ERROR) - }) + val e = assertThrows { companyService.retrieve() } + + assertThat(e.statusCode()).isEqualTo(403) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun companiesRetrieve403() { - val params = HrisCompanyRetrieveParams.builder().build() - + fun companyRetrieve404() { + val companyService = client.hris().company() stubFor( get(anyUrl()) - .willReturn(status(403).withHeader("Foo", "Bar").withBody(toJson(FINCH_ERROR))) + .willReturn( + status(404).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.hris().company().retrieve(params) }) - .satisfies({ e -> - assertPermissionDenied(e, Headers.builder().put("Foo", "Bar").build(), FINCH_ERROR) - }) + val e = assertThrows { companyService.retrieve() } + + assertThat(e.statusCode()).isEqualTo(404) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun companiesRetrieve404() { - val params = HrisCompanyRetrieveParams.builder().build() - + fun companyRetrieve422() { + val companyService = client.hris().company() stubFor( get(anyUrl()) - .willReturn(status(404).withHeader("Foo", "Bar").withBody(toJson(FINCH_ERROR))) + .willReturn( + status(422).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.hris().company().retrieve(params) }) - .satisfies({ e -> - assertNotFound(e, Headers.builder().put("Foo", "Bar").build(), FINCH_ERROR) - }) + val e = assertThrows { companyService.retrieve() } + + assertThat(e.statusCode()).isEqualTo(422) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun companiesRetrieve422() { - val params = HrisCompanyRetrieveParams.builder().build() - + fun companyRetrieve429() { + val companyService = client.hris().company() stubFor( get(anyUrl()) - .willReturn(status(422).withHeader("Foo", "Bar").withBody(toJson(FINCH_ERROR))) + .willReturn( + status(429).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.hris().company().retrieve(params) }) - .satisfies({ e -> - assertUnprocessableEntity( - e, - Headers.builder().put("Foo", "Bar").build(), - FINCH_ERROR, - ) - }) + val e = assertThrows { companyService.retrieve() } + + assertThat(e.statusCode()).isEqualTo(429) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun companiesRetrieve429() { - val params = HrisCompanyRetrieveParams.builder().build() - + fun companyRetrieve500() { + val companyService = client.hris().company() stubFor( get(anyUrl()) - .willReturn(status(429).withHeader("Foo", "Bar").withBody(toJson(FINCH_ERROR))) + .willReturn( + status(500).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.hris().company().retrieve(params) }) - .satisfies({ e -> - assertRateLimit(e, Headers.builder().put("Foo", "Bar").build(), FINCH_ERROR) - }) + val e = assertThrows { companyService.retrieve() } + + assertThat(e.statusCode()).isEqualTo(500) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun companiesRetrieve500() { - val params = HrisCompanyRetrieveParams.builder().build() - + fun companyRetrieve999() { + val companyService = client.hris().company() stubFor( get(anyUrl()) - .willReturn(status(500).withHeader("Foo", "Bar").withBody(toJson(FINCH_ERROR))) + .willReturn( + status(999).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.hris().company().retrieve(params) }) - .satisfies({ e -> - assertInternalServer(e, Headers.builder().put("Foo", "Bar").build(), FINCH_ERROR) - }) + val e = assertThrows { companyService.retrieve() } + + assertThat(e.statusCode()).isEqualTo(999) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun unexpectedStatusCode() { - val params = HrisCompanyRetrieveParams.builder().build() - + fun companyRetrieveInvalidJsonBody() { + val companyService = client.hris().company() stubFor( get(anyUrl()) - .willReturn(status(999).withHeader("Foo", "Bar").withBody(toJson(FINCH_ERROR))) + .willReturn(status(200).withHeader(HEADER_NAME, HEADER_VALUE).withBody(NOT_JSON)) ) - assertThatThrownBy({ client.hris().company().retrieve(params) }) - .satisfies({ e -> - assertUnexpectedStatusCodeException( - e, - 999, - Headers.builder().put("Foo", "Bar").build(), - toJson(FINCH_ERROR), - ) - }) - } - - @Test - fun invalidBody() { - val params = HrisCompanyRetrieveParams.builder().build() - - stubFor(get(anyUrl()).willReturn(status(200).withBody("Not JSON"))) - - assertThatThrownBy({ client.hris().company().retrieve(params) }) - .satisfies({ e -> - assertThat(e) - .isInstanceOf(FinchException::class.java) - .hasMessage("Error reading response") - }) - } - - @Test - fun invalidErrorBody() { - val params = HrisCompanyRetrieveParams.builder().build() - - stubFor(get(anyUrl()).willReturn(status(400).withBody("Not JSON"))) - - assertThatThrownBy({ client.hris().company().retrieve(params) }) - .satisfies({ e -> - assertBadRequest(e, Headers.builder().build(), FinchError.builder().build()) - }) - } - - private fun toJson(body: T): ByteArray { - return JSON_MAPPER.writeValueAsBytes(body) - } - - private fun assertUnexpectedStatusCodeException( - throwable: Throwable, - statusCode: Int, - headers: Headers, - responseBody: ByteArray, - ) { - assertThat(throwable) - .asInstanceOf( - InstanceOfAssertFactories.throwable(UnexpectedStatusCodeException::class.java) - ) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(statusCode) - assertThat(e.body()).isEqualTo(String(responseBody)) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) - } - - private fun assertBadRequest(throwable: Throwable, headers: Headers, error: FinchError) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(BadRequestException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(400) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) - } - - private fun assertUnauthorized(throwable: Throwable, headers: Headers, error: FinchError) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(UnauthorizedException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(401) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) - } - - private fun assertPermissionDenied(throwable: Throwable, headers: Headers, error: FinchError) { - assertThat(throwable) - .asInstanceOf( - InstanceOfAssertFactories.throwable(PermissionDeniedException::class.java) - ) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(403) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) - } - - private fun assertNotFound(throwable: Throwable, headers: Headers, error: FinchError) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(NotFoundException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(404) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) - } - - private fun assertUnprocessableEntity( - throwable: Throwable, - headers: Headers, - error: FinchError, - ) { - assertThat(throwable) - .asInstanceOf( - InstanceOfAssertFactories.throwable(UnprocessableEntityException::class.java) - ) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(422) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) - } - - private fun assertRateLimit(throwable: Throwable, headers: Headers, error: FinchError) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(RateLimitException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(429) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) - } + val e = assertThrows { companyService.retrieve() } - private fun assertInternalServer(throwable: Throwable, headers: Headers, error: FinchError) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(InternalServerException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(500) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers().toMap()).containsAllEntriesOf(headers.toMap()) - }) + assertThat(e).hasMessage("Error reading response") } private fun Headers.toMap(): Map> = diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/AccessTokenServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/AccessTokenServiceAsyncTest.kt index 32d058d1..2c9a0a83 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/AccessTokenServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/AccessTokenServiceAsyncTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class AccessTokenServiceAsyncTest { +internal class AccessTokenServiceAsyncTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/AccountServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/AccountServiceAsyncTest.kt index 62020a50..486debf9 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/AccountServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/AccountServiceAsyncTest.kt @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class AccountServiceAsyncTest { +internal class AccountServiceAsyncTest { @Test fun disconnect() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/ProviderServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/ProviderServiceAsyncTest.kt index 970a3878..a929fd64 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/ProviderServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/ProviderServiceAsyncTest.kt @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class ProviderServiceAsyncTest { +internal class ProviderServiceAsyncTest { @Test fun list() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/RequestForwardingServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/RequestForwardingServiceAsyncTest.kt index a30f22d6..fe0ef7f9 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/RequestForwardingServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/RequestForwardingServiceAsyncTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class RequestForwardingServiceAsyncTest { +internal class RequestForwardingServiceAsyncTest { @Test fun forward() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/connect/SessionServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/connect/SessionServiceAsyncTest.kt index 87f1d9a0..05610d63 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/connect/SessionServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/connect/SessionServiceAsyncTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class SessionServiceAsyncTest { +internal class SessionServiceAsyncTest { @Test fun new_() { @@ -27,7 +27,7 @@ class SessionServiceAsyncTest { .customerId("x") .customerName("x") .addProduct(ConnectSessionNewParams.ConnectProducts.COMPANY) - .customerEmail("dev@stainlessapi.com") + .customerEmail("dev@stainless.com") .integration( ConnectSessionNewParams.Integration.builder() .authMethod(ConnectSessionNewParams.Integration.AuthMethod.ASSISTED) diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/BenefitServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/BenefitServiceAsyncTest.kt index 8c2a73eb..549630a8 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/BenefitServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/BenefitServiceAsyncTest.kt @@ -13,7 +13,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class BenefitServiceAsyncTest { +internal class BenefitServiceAsyncTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/CompanyServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/CompanyServiceAsyncTest.kt index f281cf88..b2b53d52 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/CompanyServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/CompanyServiceAsyncTest.kt @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class CompanyServiceAsyncTest { +internal class CompanyServiceAsyncTest { @Test fun retrieve() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/DirectoryServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/DirectoryServiceAsyncTest.kt index 82958815..d6453a09 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/DirectoryServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/DirectoryServiceAsyncTest.kt @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class DirectoryServiceAsyncTest { +internal class DirectoryServiceAsyncTest { @Test fun list() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/DocumentServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/DocumentServiceAsyncTest.kt index efb50717..5dce15e3 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/DocumentServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/DocumentServiceAsyncTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class DocumentServiceAsyncTest { +internal class DocumentServiceAsyncTest { @Test fun list() { @@ -21,7 +21,7 @@ class DocumentServiceAsyncTest { .build() val documentServiceAsync = client.hris().documents() - val documentFuture = + val documentsFuture = documentServiceAsync.list( HrisDocumentListParams.builder() .addIndividualId("string") @@ -31,8 +31,8 @@ class DocumentServiceAsyncTest { .build() ) - val document = documentFuture.get() - document.validate() + val documents = documentsFuture.get() + documents.validate() } @Test diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/EmploymentServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/EmploymentServiceAsyncTest.kt index 1a201342..0bb8b214 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/EmploymentServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/EmploymentServiceAsyncTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class EmploymentServiceAsyncTest { +internal class EmploymentServiceAsyncTest { @Test fun retrieveMany() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/IndividualServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/IndividualServiceAsyncTest.kt index 5c9271e4..1bb5caf8 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/IndividualServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/IndividualServiceAsyncTest.kt @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class IndividualServiceAsyncTest { +internal class IndividualServiceAsyncTest { @Test fun retrieveMany() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/PayStatementServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/PayStatementServiceAsyncTest.kt index 20ec632a..7e582c59 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/PayStatementServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/PayStatementServiceAsyncTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class PayStatementServiceAsyncTest { +internal class PayStatementServiceAsyncTest { @Test fun retrieveMany() { @@ -25,7 +25,7 @@ class PayStatementServiceAsyncTest { HrisPayStatementRetrieveManyParams.builder() .addRequest( HrisPayStatementRetrieveManyParams.Request.builder() - .paymentId("string") + .paymentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() ) .build() diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/PaymentServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/PaymentServiceAsyncTest.kt index 3525074f..8d872e71 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/PaymentServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/PaymentServiceAsyncTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class PaymentServiceAsyncTest { +internal class PaymentServiceAsyncTest { @Test fun list() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/benefits/IndividualServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/benefits/IndividualServiceAsyncTest.kt index e2e0ba6a..28f057fa 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/benefits/IndividualServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/benefits/IndividualServiceAsyncTest.kt @@ -11,7 +11,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class IndividualServiceAsyncTest { +internal class IndividualServiceAsyncTest { @Test fun enrolledIds() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/company/PayStatementItemServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/company/PayStatementItemServiceAsyncTest.kt new file mode 100644 index 00000000..2e3dfe28 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/company/PayStatementItemServiceAsyncTest.kt @@ -0,0 +1,27 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.services.async.hris.company + +import com.tryfinch.api.TestServerExtension +import com.tryfinch.api.client.okhttp.FinchOkHttpClientAsync +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class PayStatementItemServiceAsyncTest { + + @Test + fun list() { + val client = + FinchOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .accessToken("My Access Token") + .build() + val payStatementItemServiceAsync = client.hris().company().payStatementItem() + + val pageFuture = payStatementItemServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/company/payStatementItem/RuleServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/company/payStatementItem/RuleServiceAsyncTest.kt new file mode 100644 index 00000000..d2089357 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/hris/company/payStatementItem/RuleServiceAsyncTest.kt @@ -0,0 +1,114 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.services.async.hris.company.payStatementItem + +import com.tryfinch.api.TestServerExtension +import com.tryfinch.api.client.okhttp.FinchOkHttpClientAsync +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleCreateParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleDeleteParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class RuleServiceAsyncTest { + + @Test + fun create() { + val client = + FinchOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .accessToken("My Access Token") + .build() + val ruleServiceAsync = client.hris().company().payStatementItem().rules() + + val ruleFuture = + ruleServiceAsync.create( + HrisCompanyPayStatementItemRuleCreateParams.builder() + .attributes( + HrisCompanyPayStatementItemRuleCreateParams.Attributes.builder() + .metadata( + HrisCompanyPayStatementItemRuleCreateParams.Attributes.Metadata + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .addCondition( + HrisCompanyPayStatementItemRuleCreateParams.Condition.builder() + .field("field") + .operator( + HrisCompanyPayStatementItemRuleCreateParams.Condition.Operator + .EQUALS + ) + .value("value") + .build() + ) + .effectiveEndDate("effective_end_date") + .effectiveStartDate("effective_start_date") + .entityType( + HrisCompanyPayStatementItemRuleCreateParams.EntityType.PAY_STATEMENT_ITEM + ) + .build() + ) + + val rule = ruleFuture.get() + rule.validate() + } + + @Test + fun update() { + val client = + FinchOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .accessToken("My Access Token") + .build() + val ruleServiceAsync = client.hris().company().payStatementItem().rules() + + val ruleFuture = + ruleServiceAsync.update( + HrisCompanyPayStatementItemRuleUpdateParams.builder() + .ruleId("rule_id") + .optionalProperty(JsonValue.from(mapOf())) + .build() + ) + + val rule = ruleFuture.get() + rule.validate() + } + + @Test + fun list() { + val client = + FinchOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .accessToken("My Access Token") + .build() + val ruleServiceAsync = client.hris().company().payStatementItem().rules() + + val pageFuture = ruleServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + FinchOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .accessToken("My Access Token") + .build() + val ruleServiceAsync = client.hris().company().payStatementItem().rules() + + val ruleFuture = + ruleServiceAsync.delete( + HrisCompanyPayStatementItemRuleDeleteParams.builder().ruleId("rule_id").build() + ) + + val rule = ruleFuture.get() + rule.validate() + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/jobs/AutomatedServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/jobs/AutomatedServiceAsyncTest.kt index 305e344f..8eea4c25 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/jobs/AutomatedServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/jobs/AutomatedServiceAsyncTest.kt @@ -5,12 +5,13 @@ package com.tryfinch.api.services.async.jobs import com.tryfinch.api.TestServerExtension import com.tryfinch.api.client.okhttp.FinchOkHttpClientAsync import com.tryfinch.api.models.JobAutomatedCreateParams +import com.tryfinch.api.models.JobAutomatedListParams import com.tryfinch.api.models.JobAutomatedRetrieveParams import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class AutomatedServiceAsyncTest { +internal class AutomatedServiceAsyncTest { @Test fun create() { @@ -63,9 +64,12 @@ class AutomatedServiceAsyncTest { .build() val automatedServiceAsync = client.jobs().automated() - val pageFuture = automatedServiceAsync.list() + val automatedsFuture = + automatedServiceAsync.list( + JobAutomatedListParams.builder().limit(0L).offset(0L).build() + ) - val page = pageFuture.get() - page.response().validate() + val automateds = automatedsFuture.get() + automateds.validate() } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/jobs/ManualServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/jobs/ManualServiceAsyncTest.kt index b0e5e66f..5a095fad 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/jobs/ManualServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/jobs/ManualServiceAsyncTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class ManualServiceAsyncTest { +internal class ManualServiceAsyncTest { @Test fun retrieve() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/payroll/PayGroupServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/payroll/PayGroupServiceAsyncTest.kt index 603c5607..c7bf8d63 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/payroll/PayGroupServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/payroll/PayGroupServiceAsyncTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class PayGroupServiceAsyncTest { +internal class PayGroupServiceAsyncTest { @Test fun retrieve() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/CompanyServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/CompanyServiceAsyncTest.kt index e4a8d339..644fb0d1 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/CompanyServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/CompanyServiceAsyncTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class CompanyServiceAsyncTest { +internal class CompanyServiceAsyncTest { @Test fun update() { @@ -63,7 +63,7 @@ class CompanyServiceAsyncTest { .state("state") .build() ) - .primaryEmail("primary_email") + .primaryEmail("dev@stainless.com") .primaryPhoneNumber("primary_phone_number") .build() ) diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/ConnectionServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/ConnectionServiceAsyncTest.kt index d642684f..197e0ec5 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/ConnectionServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/ConnectionServiceAsyncTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class ConnectionServiceAsyncTest { +internal class ConnectionServiceAsyncTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/DirectoryServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/DirectoryServiceAsyncTest.kt index c6c5da92..5572fa2d 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/DirectoryServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/DirectoryServiceAsyncTest.kt @@ -12,7 +12,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class DirectoryServiceAsyncTest { +internal class DirectoryServiceAsyncTest { @Test fun create() { @@ -117,7 +117,7 @@ class DirectoryServiceAsyncTest { .manager( SandboxDirectoryCreateParams.IndividualOrEmployment.Manager .builder() - .id("id") + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() ) .middleName("middle_name") @@ -156,5 +156,6 @@ class DirectoryServiceAsyncTest { ) val directories = directoriesFuture.get() + directories.forEach { it.validate() } } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/EmploymentServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/EmploymentServiceAsyncTest.kt index 406c6e9b..e85386fd 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/EmploymentServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/EmploymentServiceAsyncTest.kt @@ -12,7 +12,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class EmploymentServiceAsyncTest { +internal class EmploymentServiceAsyncTest { @Test fun update() { @@ -77,7 +77,11 @@ class EmploymentServiceAsyncTest { .state("state") .build() ) - .manager(SandboxEmploymentUpdateParams.Manager.builder().id("id").build()) + .manager( + SandboxEmploymentUpdateParams.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) .middleName("middle_name") .sourceId("source_id") .startDate("start_date") diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/IndividualServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/IndividualServiceAsyncTest.kt index e7b71dc4..7f489dbe 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/IndividualServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/IndividualServiceAsyncTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class IndividualServiceAsyncTest { +internal class IndividualServiceAsyncTest { @Test fun update() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/JobServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/JobServiceAsyncTest.kt index 157e7459..16fde9f4 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/JobServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/JobServiceAsyncTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class JobServiceAsyncTest { +internal class JobServiceAsyncTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/PaymentServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/PaymentServiceAsyncTest.kt index 88fdddfe..1faf4d8a 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/PaymentServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/PaymentServiceAsyncTest.kt @@ -12,7 +12,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class PaymentServiceAsyncTest { +internal class PaymentServiceAsyncTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/connections/AccountServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/connections/AccountServiceAsyncTest.kt index 6e7732ce..c45deebb 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/connections/AccountServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/connections/AccountServiceAsyncTest.kt @@ -11,7 +11,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class AccountServiceAsyncTest { +internal class AccountServiceAsyncTest { @Test fun create() { @@ -50,7 +50,7 @@ class AccountServiceAsyncTest { val accountFuture = accountServiceAsync.update( SandboxConnectionAccountUpdateParams.builder() - .connectionStatus(ConnectionStatusType.PENDING) + .connectionStatus(ConnectionStatusType.REAUTH) .build() ) diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/jobs/ConfigurationServiceAsyncTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/jobs/ConfigurationServiceAsyncTest.kt index c219443c..e7181ea2 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/jobs/ConfigurationServiceAsyncTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/async/sandbox/jobs/ConfigurationServiceAsyncTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class ConfigurationServiceAsyncTest { +internal class ConfigurationServiceAsyncTest { @Test fun retrieve() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/AccessTokenServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/AccessTokenServiceTest.kt index c015937d..68a7c439 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/AccessTokenServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/AccessTokenServiceTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class AccessTokenServiceTest { +internal class AccessTokenServiceTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/AccountServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/AccountServiceTest.kt index d3b6eab2..adb69330 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/AccountServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/AccountServiceTest.kt @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class AccountServiceTest { +internal class AccountServiceTest { @Test fun disconnect() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/ProviderServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/ProviderServiceTest.kt index 061ba5ac..ef8de16e 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/ProviderServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/ProviderServiceTest.kt @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class ProviderServiceTest { +internal class ProviderServiceTest { @Test fun list() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/RequestForwardingServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/RequestForwardingServiceTest.kt index ea604816..a68eed63 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/RequestForwardingServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/RequestForwardingServiceTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class RequestForwardingServiceTest { +internal class RequestForwardingServiceTest { @Test fun forward() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/connect/SessionServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/connect/SessionServiceTest.kt index a7d71d39..276f3066 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/connect/SessionServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/connect/SessionServiceTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class SessionServiceTest { +internal class SessionServiceTest { @Test fun new_() { @@ -27,7 +27,7 @@ class SessionServiceTest { .customerId("x") .customerName("x") .addProduct(ConnectSessionNewParams.ConnectProducts.COMPANY) - .customerEmail("dev@stainlessapi.com") + .customerEmail("dev@stainless.com") .integration( ConnectSessionNewParams.Integration.builder() .authMethod(ConnectSessionNewParams.Integration.AuthMethod.ASSISTED) diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/BenefitServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/BenefitServiceTest.kt index 488bfb34..e4b2635e 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/BenefitServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/BenefitServiceTest.kt @@ -13,7 +13,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class BenefitServiceTest { +internal class BenefitServiceTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/CompanyServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/CompanyServiceTest.kt index 79040ece..40988679 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/CompanyServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/CompanyServiceTest.kt @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class CompanyServiceTest { +internal class CompanyServiceTest { @Test fun retrieve() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/DirectoryServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/DirectoryServiceTest.kt index 61039c9e..a5417bd6 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/DirectoryServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/DirectoryServiceTest.kt @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class DirectoryServiceTest { +internal class DirectoryServiceTest { @Test fun list() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/DocumentServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/DocumentServiceTest.kt index aee56e24..4faa8f0a 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/DocumentServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/DocumentServiceTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class DocumentServiceTest { +internal class DocumentServiceTest { @Test fun list() { @@ -21,7 +21,7 @@ class DocumentServiceTest { .build() val documentService = client.hris().documents() - val document = + val documents = documentService.list( HrisDocumentListParams.builder() .addIndividualId("string") @@ -31,7 +31,7 @@ class DocumentServiceTest { .build() ) - document.validate() + documents.validate() } @Test diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/EmploymentServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/EmploymentServiceTest.kt index 1de19a6e..f36ea0d8 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/EmploymentServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/EmploymentServiceTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class EmploymentServiceTest { +internal class EmploymentServiceTest { @Test fun retrieveMany() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/IndividualServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/IndividualServiceTest.kt index 229dbb1a..83d763cf 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/IndividualServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/IndividualServiceTest.kt @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class IndividualServiceTest { +internal class IndividualServiceTest { @Test fun retrieveMany() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/PayStatementServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/PayStatementServiceTest.kt index 625767fa..cca8bd08 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/PayStatementServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/PayStatementServiceTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class PayStatementServiceTest { +internal class PayStatementServiceTest { @Test fun retrieveMany() { @@ -25,7 +25,7 @@ class PayStatementServiceTest { HrisPayStatementRetrieveManyParams.builder() .addRequest( HrisPayStatementRetrieveManyParams.Request.builder() - .paymentId("string") + .paymentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() ) .build() diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/PaymentServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/PaymentServiceTest.kt index dcdb6295..81898391 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/PaymentServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/PaymentServiceTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class PaymentServiceTest { +internal class PaymentServiceTest { @Test fun list() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/benefits/IndividualServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/benefits/IndividualServiceTest.kt index 7f39fa58..14051f3f 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/benefits/IndividualServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/benefits/IndividualServiceTest.kt @@ -11,7 +11,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class IndividualServiceTest { +internal class IndividualServiceTest { @Test fun enrolledIds() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/company/PayStatementItemServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/company/PayStatementItemServiceTest.kt new file mode 100644 index 00000000..f5a32058 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/company/PayStatementItemServiceTest.kt @@ -0,0 +1,26 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.services.blocking.hris.company + +import com.tryfinch.api.TestServerExtension +import com.tryfinch.api.client.okhttp.FinchOkHttpClient +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class PayStatementItemServiceTest { + + @Test + fun list() { + val client = + FinchOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .accessToken("My Access Token") + .build() + val payStatementItemService = client.hris().company().payStatementItem() + + val page = payStatementItemService.list() + + page.response().validate() + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/company/payStatementItem/RuleServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/company/payStatementItem/RuleServiceTest.kt new file mode 100644 index 00000000..be36e133 --- /dev/null +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/hris/company/payStatementItem/RuleServiceTest.kt @@ -0,0 +1,110 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.tryfinch.api.services.blocking.hris.company.payStatementItem + +import com.tryfinch.api.TestServerExtension +import com.tryfinch.api.client.okhttp.FinchOkHttpClient +import com.tryfinch.api.core.JsonValue +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleCreateParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleDeleteParams +import com.tryfinch.api.models.HrisCompanyPayStatementItemRuleUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class RuleServiceTest { + + @Test + fun create() { + val client = + FinchOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .accessToken("My Access Token") + .build() + val ruleService = client.hris().company().payStatementItem().rules() + + val rule = + ruleService.create( + HrisCompanyPayStatementItemRuleCreateParams.builder() + .attributes( + HrisCompanyPayStatementItemRuleCreateParams.Attributes.builder() + .metadata( + HrisCompanyPayStatementItemRuleCreateParams.Attributes.Metadata + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .addCondition( + HrisCompanyPayStatementItemRuleCreateParams.Condition.builder() + .field("field") + .operator( + HrisCompanyPayStatementItemRuleCreateParams.Condition.Operator + .EQUALS + ) + .value("value") + .build() + ) + .effectiveEndDate("effective_end_date") + .effectiveStartDate("effective_start_date") + .entityType( + HrisCompanyPayStatementItemRuleCreateParams.EntityType.PAY_STATEMENT_ITEM + ) + .build() + ) + + rule.validate() + } + + @Test + fun update() { + val client = + FinchOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .accessToken("My Access Token") + .build() + val ruleService = client.hris().company().payStatementItem().rules() + + val rule = + ruleService.update( + HrisCompanyPayStatementItemRuleUpdateParams.builder() + .ruleId("rule_id") + .optionalProperty(JsonValue.from(mapOf())) + .build() + ) + + rule.validate() + } + + @Test + fun list() { + val client = + FinchOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .accessToken("My Access Token") + .build() + val ruleService = client.hris().company().payStatementItem().rules() + + val page = ruleService.list() + + page.response().validate() + } + + @Test + fun delete() { + val client = + FinchOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .accessToken("My Access Token") + .build() + val ruleService = client.hris().company().payStatementItem().rules() + + val rule = + ruleService.delete( + HrisCompanyPayStatementItemRuleDeleteParams.builder().ruleId("rule_id").build() + ) + + rule.validate() + } +} diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/jobs/AutomatedServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/jobs/AutomatedServiceTest.kt index 087d29b4..226173ab 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/jobs/AutomatedServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/jobs/AutomatedServiceTest.kt @@ -5,12 +5,13 @@ package com.tryfinch.api.services.blocking.jobs import com.tryfinch.api.TestServerExtension import com.tryfinch.api.client.okhttp.FinchOkHttpClient import com.tryfinch.api.models.JobAutomatedCreateParams +import com.tryfinch.api.models.JobAutomatedListParams import com.tryfinch.api.models.JobAutomatedRetrieveParams import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class AutomatedServiceTest { +internal class AutomatedServiceTest { @Test fun create() { @@ -59,8 +60,9 @@ class AutomatedServiceTest { .build() val automatedService = client.jobs().automated() - val page = automatedService.list() + val automateds = + automatedService.list(JobAutomatedListParams.builder().limit(0L).offset(0L).build()) - page.response().validate() + automateds.validate() } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/jobs/ManualServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/jobs/ManualServiceTest.kt index fcf6a74d..3ad62102 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/jobs/ManualServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/jobs/ManualServiceTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class ManualServiceTest { +internal class ManualServiceTest { @Test fun retrieve() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/payroll/PayGroupServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/payroll/PayGroupServiceTest.kt index 569dfb08..5c257d37 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/payroll/PayGroupServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/payroll/PayGroupServiceTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class PayGroupServiceTest { +internal class PayGroupServiceTest { @Test fun retrieve() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/CompanyServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/CompanyServiceTest.kt index e16c0ee9..092485b9 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/CompanyServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/CompanyServiceTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class CompanyServiceTest { +internal class CompanyServiceTest { @Test fun update() { @@ -63,7 +63,7 @@ class CompanyServiceTest { .state("state") .build() ) - .primaryEmail("primary_email") + .primaryEmail("dev@stainless.com") .primaryPhoneNumber("primary_phone_number") .build() ) diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/ConnectionServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/ConnectionServiceTest.kt index c310e2cc..af59feec 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/ConnectionServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/ConnectionServiceTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class ConnectionServiceTest { +internal class ConnectionServiceTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/DirectoryServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/DirectoryServiceTest.kt index bd96b1f1..dc3d0a26 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/DirectoryServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/DirectoryServiceTest.kt @@ -12,7 +12,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class DirectoryServiceTest { +internal class DirectoryServiceTest { @Test fun create() { @@ -23,126 +23,138 @@ class DirectoryServiceTest { .build() val directoryService = client.sandbox().directory() - directoryService.create( - SandboxDirectoryCreateParams.builder() - .addBody( - SandboxDirectoryCreateParams.IndividualOrEmployment.builder() - .classCode("class_code") - .addCustomField( - SandboxDirectoryCreateParams.IndividualOrEmployment.CustomField - .builder() - .name("name") - .value(JsonValue.from(mapOf())) - .build() - ) - .department( - SandboxDirectoryCreateParams.IndividualOrEmployment.Department.builder() - .name("name") - .build() - ) - .dob("dob") - .addEmail( - SandboxDirectoryCreateParams.IndividualOrEmployment.Email.builder() - .data("data") - .type( - SandboxDirectoryCreateParams.IndividualOrEmployment.Email.Type - .WORK - ) - .build() - ) - .employment( - SandboxDirectoryCreateParams.IndividualOrEmployment.Employment.builder() - .subtype( - SandboxDirectoryCreateParams.IndividualOrEmployment.Employment - .Subtype - .FULL_TIME - ) - .type( - SandboxDirectoryCreateParams.IndividualOrEmployment.Employment - .Type - .EMPLOYEE - ) - .build() - ) - .employmentStatus( - SandboxDirectoryCreateParams.IndividualOrEmployment.EmploymentStatus - .ACTIVE - ) - .encryptedSsn("encrypted_ssn") - .endDate("end_date") - .ethnicity( - SandboxDirectoryCreateParams.IndividualOrEmployment.Ethnicity.ASIAN - ) - .firstName("first_name") - .gender(SandboxDirectoryCreateParams.IndividualOrEmployment.Gender.FEMALE) - .income( - Income.builder() - .amount(0L) - .currency("currency") - .effectiveDate("effective_date") - .unit(Income.Unit.YEARLY) - .build() - ) - .addIncomeHistory( - Income.builder() - .amount(0L) - .currency("currency") - .effectiveDate("effective_date") - .unit(Income.Unit.YEARLY) - .build() - ) - .isActive(true) - .lastName("last_name") - .latestRehireDate("latest_rehire_date") - .location( - Location.builder() - .city("city") - .country("country") - .line1("line1") - .line2("line2") - .name("name") - .postalCode("postal_code") - .sourceId("source_id") - .state("state") - .build() - ) - .manager( - SandboxDirectoryCreateParams.IndividualOrEmployment.Manager.builder() - .id("id") - .build() - ) - .middleName("middle_name") - .addPhoneNumber( - SandboxDirectoryCreateParams.IndividualOrEmployment.PhoneNumber - .builder() - .data("data") - .type( - SandboxDirectoryCreateParams.IndividualOrEmployment.PhoneNumber - .Type - .WORK - ) - .build() - ) - .preferredName("preferred_name") - .residence( - Location.builder() - .city("city") - .country("country") - .line1("line1") - .line2("line2") - .name("name") - .postalCode("postal_code") - .sourceId("source_id") - .state("state") - .build() - ) - .sourceId("source_id") - .ssn("ssn") - .startDate("start_date") - .title("title") - .build() - ) - .build() - ) + val directories = + directoryService.create( + SandboxDirectoryCreateParams.builder() + .addBody( + SandboxDirectoryCreateParams.IndividualOrEmployment.builder() + .classCode("class_code") + .addCustomField( + SandboxDirectoryCreateParams.IndividualOrEmployment.CustomField + .builder() + .name("name") + .value(JsonValue.from(mapOf())) + .build() + ) + .department( + SandboxDirectoryCreateParams.IndividualOrEmployment.Department + .builder() + .name("name") + .build() + ) + .dob("dob") + .addEmail( + SandboxDirectoryCreateParams.IndividualOrEmployment.Email.builder() + .data("data") + .type( + SandboxDirectoryCreateParams.IndividualOrEmployment.Email + .Type + .WORK + ) + .build() + ) + .employment( + SandboxDirectoryCreateParams.IndividualOrEmployment.Employment + .builder() + .subtype( + SandboxDirectoryCreateParams.IndividualOrEmployment + .Employment + .Subtype + .FULL_TIME + ) + .type( + SandboxDirectoryCreateParams.IndividualOrEmployment + .Employment + .Type + .EMPLOYEE + ) + .build() + ) + .employmentStatus( + SandboxDirectoryCreateParams.IndividualOrEmployment.EmploymentStatus + .ACTIVE + ) + .encryptedSsn("encrypted_ssn") + .endDate("end_date") + .ethnicity( + SandboxDirectoryCreateParams.IndividualOrEmployment.Ethnicity.ASIAN + ) + .firstName("first_name") + .gender( + SandboxDirectoryCreateParams.IndividualOrEmployment.Gender.FEMALE + ) + .income( + Income.builder() + .amount(0L) + .currency("currency") + .effectiveDate("effective_date") + .unit(Income.Unit.YEARLY) + .build() + ) + .addIncomeHistory( + Income.builder() + .amount(0L) + .currency("currency") + .effectiveDate("effective_date") + .unit(Income.Unit.YEARLY) + .build() + ) + .isActive(true) + .lastName("last_name") + .latestRehireDate("latest_rehire_date") + .location( + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() + ) + .manager( + SandboxDirectoryCreateParams.IndividualOrEmployment.Manager + .builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .middleName("middle_name") + .addPhoneNumber( + SandboxDirectoryCreateParams.IndividualOrEmployment.PhoneNumber + .builder() + .data("data") + .type( + SandboxDirectoryCreateParams.IndividualOrEmployment + .PhoneNumber + .Type + .WORK + ) + .build() + ) + .preferredName("preferred_name") + .residence( + Location.builder() + .city("city") + .country("country") + .line1("line1") + .line2("line2") + .name("name") + .postalCode("postal_code") + .sourceId("source_id") + .state("state") + .build() + ) + .sourceId("source_id") + .ssn("ssn") + .startDate("start_date") + .title("title") + .build() + ) + .build() + ) + + directories.forEach { it.validate() } } } diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/EmploymentServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/EmploymentServiceTest.kt index 578cfb42..a14004ae 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/EmploymentServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/EmploymentServiceTest.kt @@ -12,7 +12,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class EmploymentServiceTest { +internal class EmploymentServiceTest { @Test fun update() { @@ -77,7 +77,11 @@ class EmploymentServiceTest { .state("state") .build() ) - .manager(SandboxEmploymentUpdateParams.Manager.builder().id("id").build()) + .manager( + SandboxEmploymentUpdateParams.Manager.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) .middleName("middle_name") .sourceId("source_id") .startDate("start_date") diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/IndividualServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/IndividualServiceTest.kt index 6171b984..d4138d0c 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/IndividualServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/IndividualServiceTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class IndividualServiceTest { +internal class IndividualServiceTest { @Test fun update() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/JobServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/JobServiceTest.kt index b196352b..b277cd6f 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/JobServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/JobServiceTest.kt @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class JobServiceTest { +internal class JobServiceTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/PaymentServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/PaymentServiceTest.kt index 3d7751cd..3d67e68e 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/PaymentServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/PaymentServiceTest.kt @@ -12,7 +12,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class PaymentServiceTest { +internal class PaymentServiceTest { @Test fun create() { diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/connections/AccountServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/connections/AccountServiceTest.kt index 2b427d6c..5cf6c67d 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/connections/AccountServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/connections/AccountServiceTest.kt @@ -11,7 +11,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class AccountServiceTest { +internal class AccountServiceTest { @Test fun create() { @@ -49,7 +49,7 @@ class AccountServiceTest { val account = accountService.update( SandboxConnectionAccountUpdateParams.builder() - .connectionStatus(ConnectionStatusType.PENDING) + .connectionStatus(ConnectionStatusType.REAUTH) .build() ) diff --git a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/jobs/ConfigurationServiceTest.kt b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/jobs/ConfigurationServiceTest.kt index 12e59369..64cd3fad 100644 --- a/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/jobs/ConfigurationServiceTest.kt +++ b/finch-java-core/src/test/kotlin/com/tryfinch/api/services/blocking/sandbox/jobs/ConfigurationServiceTest.kt @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class ConfigurationServiceTest { +internal class ConfigurationServiceTest { @Test fun retrieve() { diff --git a/finch-java-example/build.gradle.kts b/finch-java-example/build.gradle.kts index 29e65075..bfcda061 100644 --- a/finch-java-example/build.gradle.kts +++ b/finch-java-example/build.gradle.kts @@ -1,9 +1,12 @@ plugins { - id("finch.kotlin") - id("java") + id("finch.java") application } +repositories { + mavenCentral() +} + dependencies { implementation(project(":finch-java")) } diff --git a/finch-java/build.gradle.kts b/finch-java/build.gradle.kts index b12d5c3e..8f48de09 100644 --- a/finch-java/build.gradle.kts +++ b/finch-java/build.gradle.kts @@ -6,3 +6,24 @@ plugins { dependencies { api(project(":finch-java-client-okhttp")) } + +// Redefine `dokkaJavadoc` to: +// - Depend on the root project's task for merging the docs of all the projects +// - Forward that task's output to this task's output +tasks.named("dokkaJavadoc").configure { + actions.clear() + + val dokkaJavadocCollector = rootProject.tasks["dokkaJavadocCollector"] + dependsOn(dokkaJavadocCollector) + + val outputDirectory = project.layout.buildDirectory.dir("dokka/javadoc") + doLast { + copy { + from(dokkaJavadocCollector.outputs.files) + into(outputDirectory) + duplicatesStrategy = DuplicatesStrategy.INCLUDE + } + } + + outputs.dir(outputDirectory) +} diff --git a/release-please-config.json b/release-please-config.json index e1ea47ff..9d3ea4fe 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -69,7 +69,8 @@ "miguel-finch", "edkim-finch", "bteodosioFinch", - "ashar-finch" + "ashar-finch", + "minupalaniappan" ], "release-type": "simple", "extra-files": [